How can I write a simple email validation program in Python?

19.2k Views Asked by At

This may seem a stupid question, but how can I write a simple email validation program in Python? I'm quite new to the software and I've missed a couple of IT lessons, so I really have no idea what to do.

This is as far as I've gotten (yes, I know it doesn't do anything useful):

email = input ("Please type in an email address ")
splitemail = email.split('@')
emailstr = ''.join(splitemail)
splitemail2 = emailstr.split('.')
print (splitemail2)

The email needs to have this pattern: [alphanumeric character(s)] @ [alphanumeric character(s)] . [alphanumeric character(s)]

Then the program must determine whether is is valid or not and output 'VALID' or 'INVALID'.

Thanks for reading, and any help would be greatly appreciated.

3

There are 3 best solutions below

1
On

You can use the string.isalum() function to solve this.

example:

def validate(mystring):
    if mystring.isalnum():
        print "VALID"
    else:
        print "INVALID"

Here is an example in-out:

IN   mystring = "alphanum1234"
OUT  VALID

IN   mystring = "alpha num 1234"
OUT  INVALID

IN   mystring = "alpha.num-1234"
OUT  INVALID
4
On

Read about regex they should help you :) a useful regex for validating emails is :

[A-Za-z0-9-_]+(.[A-Za-z0-9-_]+)*@[A-Za-z0-9-]+(.[A-Za-z0-9]+)*(.[A-Za-z]{2,})

An explanation of this can be found here

Here are some good tutorials to start with for regex :

http://fr.slideshare.net/absherzad/java-regular-expression-part-i

http://fr.slideshare.net/absherzad/java-regular-expression-part-ii

And here is a question on SE concerning validating emails in python using regex

3
On

I would use some regular expressions to validate and split the given email adress. The code would then look like this

import re
email = input ("Please type in an email address ")
if re.match("\A(?P<name>[\w\-_]+)@(?P<domain>[\w\-_]+).(?P<toplevel>[\w]+)\Z",email,re.IGNORECASE):
    print("Email is valid")
else:
    print("Email is invalid")

For information aboout regualr expressions take a look here. Here a link for easily testing your expression.