Django Email Validation and Formatting

  • Share this:

Code introduction


This function first tries to validate the email address format using Django's `validate_email` function. If the email format is correct, it converts the email address to lowercase and returns it. If the email format is incorrect, it raises a `ValueError`.


Technology Stack : Django

Code Type : Verify and format emails

Code Difficulty : Intermediate


                
                    
import random
from django.core.validators import validate_email
from django.core.exceptions import ValidationError

def validate_and_format_email(email):
    """
    Validates the email address and formats it to lowercase.
    If the email is valid, it returns the formatted email; otherwise, it raises a ValueError.
    """
    try:
        validate_email(email)
        return email.lower()
    except ValidationError:
        raise ValueError("Invalid email format")                
              
Tags: