Home > database >  exclude domains regex email validation
exclude domains regex email validation

Time:09-28

So I need to validate an email address, but not just any It should follow these rules:

  1. min login length is 6 symbols
  2. login cannot start with 2 numbers
  3. domain cannot be ya.ru or ya.ua
  4. domain can have multiple levels: f.e. @google.com.ua

*I’m using Python

I only have the standard email validation regex so far.

^[\w-\.] @([\w-] \.) [\w-]{2,4}$

and 0 ideas on how to change it to get what I need. Sorry, I’m desperate Will be very thankful for any help.

CodePudding user response:

Python has logic - logic is more expressive.

def validate(email: str) -> bool:
    if '@' in email: 
        login, domain = email.split('@')
        return all([
            len(login) >= 6,
            not login[:2].isdigit(),
            not any([domain.endswith(x) for x in [
                    'ya.ru',
                    'ya.ua',
                ]
            ]),
            '.' in domain
        ])
    return False

x = validate('[email protected]')
print(x)

CodePudding user response:

I think this will fit your requirements although I'm not sure what you mean by "domain can have multiple levels".

import re

p = re.compile(r"[a-z0-9!#$%&'* /=?^_‘{| }~-] (?:\.[a-z0-9!#$%&'* /=?^_‘{|}~-] )*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.) [a-z0-9](?:[a-z0-9-]*[a-z0-9])?")

def validate(email):
    if (m := p.match(email)):
        t = email.split('@')
        if len(t[0]) < 6:
            return False
        try:
            int(t[0][0:2])
            return False
        except ValueError:
            pass
        if t[1] in ['ya.ru', 'ya.ua']:
            return False
        return True
    return False

print(validate('[email protected]'))

Note: The RE is NOT of my making. It's something I discovered a long time ago and it's what I've used ever since. Thus I am unable to give credit to the author

  • Related