View Full Version : Code to check if a input text contains "@"

01-26-2011, 03:36 PM
I have a form and i want the email input text box to have a code attached to it so if someone doesnt put a @ in it it boucnes back saying not a vaild email address. Anyone have a code what i can look at to do this/point me in the direction what to look for? Im completly new to javascript >.<

01-26-2011, 05:01 PM
You can test the field value against a regular expression. The test fails for illegal email addresses (including all characters). So this is maybe what you want:

if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(document.getElementById('fieldID').value)) {
alert('Invalid email address');

01-26-2011, 09:18 PM
Thanks ill give that a go =]. Have i read the code right? It's saying the field must contain [any character]then a @ then [more characters]? So if someone entered just '@hotmail.com' or 'tom@' it would return invalid because theres no characters before/after it?

01-26-2011, 09:27 PM
Yes, it reads like this:

- Have at least one of the characters A-Z 0-9 . _ % + -
- Have an @
- Have at least one of the characters A-Z 0-9 . -
- Have a dot
- Have at least 2 and at most 4 of the characters A-Z
- All of this case insensitive

Which made me think about a better version :-)

if (!/^[A-Z0-9._%+-]+@[A-Z0-9][A-Z0-9.-]*\.[A-Z]{2,4}$/i.test(document.getElementById('fieldID').value)) {
alert('Invalid email address');

01-26-2011, 09:41 PM
-Thank you for explaining :). Would you mind explaining what the !/^ and stuff means? I wanna learn JS next, soon as ive mastered PHP :P

01-26-2011, 10:58 PM
The // are the outer delimiters of the regex

The i after the right delimiter means "ignore case"

The //.test('...') tests if the regex matches the string '...' and returns true, if it does

The ! before all that negates the result of //.test() ... so it will be false if the regex matches and true if it doesn't (the second case is what we get for wrong email addresses)

The ^ right at the beginning of the regex means "match the beginning of the string"

The $ right at the end of the regex means "match the end of the string"

01-26-2011, 11:24 PM
Thanks :), a little confusing but im sure ill get the hang of it soon

EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum