Email Validation

Write a Python function that validates an email address and raises different custom exceptions for different invalid aspects, such as missing ‘@’, illegal characters, etc.

Example 1:

Input: "

user1@example.com

" 
Output: "Email validated successfully."

Example 2:

Input: "user1example.com" 
Output: "Error: Missing '@' in email."

Use Python’s string methods and the re module for regular expression matching.

import re

def validate_email(email):
    if "@" not in email:
        raise Exception("Error: Missing '@' in email.")
    elif not re.match(r"[^@]+@[^@]+\.[^@]+", email):
        raise Exception("Error: Invalid email.")
    else:
        return "Email validated successfully."

print(validate_email("user1@example.com"))  # Output: "Email validated successfully."
print(validate_email("user1example.com"))  # Output: "Error: Missing '@' in email."

 

© Let’s Data Science

LOGIN

Unlock AI & Data Science treasures. Log in!