Conditions for a Valid Email & Email Validation using Regex

Profile Picture

visheshnamdev72

Tuesday, 2024-08-27



The re module in Python is used for working with Regular Expressions (Regex), which are sequences of characters that define search patterns. It provides powerful tools to search, manipulate, and analyze strings based on specific patterns, making it a core utility for text processing tasks like validation, searching, extraction, or substitution in strings.



Conditions for a Valid Email📧


[Updated] Gmail signature image/logo broken for some users, issue escalated (possible workaround inside)


Eg….theroyalnamdeo@gmail.com


  1. Length of the Email: At least 6 characters long.
  2. First Character: Must be an alphabet (a-z or A-Z).
  3. Presence of "@" Symbol: Must contain exactly one "@" symbol. "@" should not be the first or last character.
  4. Presence of "." Symbol: Must contain at least one "." symbol after the "@" symbol. A "." should appear either 2 or 3 positions before the end of the email.
  5. Allowed Characters: Can include alphabets (a-z, A-Z), digits (0-9), periods (.), underscores (_), and the "@" symbol. No other special characters are allowed. Consecutive periods ("..") are not allowed.
  6. No Spaces: Must not contain any spaces.
  7. Domain Name: The part after "@" should contain at least one period. The domain name should be at least 2 characters long. The domain name should start with an alphabet.
  8. Top-Level Domain (TLD): The last part of the domain (e.g., ".com", ".org") should be between 2 and 4 characters long. TLD should only contain alphabets.
  9. No Consecutive Special Characters: There should be no consecutive special characters (e.g., "..", "@@", ".@", "@.").
  10. No Leading or Trailing Special Characters: The email should not start or end with a special character.


Cover image for how to verify email an address in 2024



Code:-

import re 

# username + "@" + domain + "." + TLD .com, .in, .org {2,3}

def validate_email(email):
    pattern = r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z]{2,3}$'


    if re.match(pattern, email):
        return True
    else:
        return False


email = input("Enter the Email: ")


if validate_email(email):
    print(f"{email} is valid!!")
else:
    print(f"{email} is not valid!!")

Thank you

How did you feel about this post?

😍 🙂 😐 😕 😡