Welcome to WebmasterWorld Guest from

Forum Moderators: open

Message Too Old, No Replies

java script Email validation

9:50 pm on Mar 20, 2012 (gmt 0)

New User

5+ Year Member

joined:Mar 20, 2012
posts: 1
votes: 0

I need to check if the user types in correct email address when user selects YES from the radio button or check boxes or whatever...

I am using this function to validate email

function validateForm()
var x=document.forms["EmailForm"]["email"].value;
var atpos=x.indexOf("@");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
alert("Not a valid e-mail address");
return false;


I dont know how to call this function when YES is selected.

Any help ? :)
6:17 am on Mar 21, 2012 (gmt 0)

New User

5+ Year Member

joined:Mar 21, 2012
posts: 7
votes: 0

I don't quite understand what you're asking. You seem to want the function to be called when the user sets some input to "on". But the function only generates an alert - if they dismiss it, then the page will not indicate that the email address is invalid. Also, why do you only want to check when the checkbox is "on"? Does "off" hide the email input?

Either way, this should get you started.

[edit: code removed and reposted here: [pastebin.com ]. webmasterworld is actually deleting segments out of it, making it impossible to post a functional webpage.]

The magic bit of code is "email.addEventListener('keyup',updateAlert);": this tells the browser to call updateAlert() whenever the input's value is changed. If you need your code to be compatible with older browsers you should also use attachEvent and .onKeyup.

Also, note that I changed your validation function to use a regular expression. This makes it quite a bit shorter, and much more robust (though it's still not perfect).
5:59 pm on Mar 21, 2012 (gmt 0)

Junior Member

5+ Year Member

joined:Feb 7, 2010
posts: 119
votes: 0

I'm opting for:
or whatever...

Recently I circled around this email validation thing for some little time ;) trying to figure every possible combination, permutation, country, .com, .us.gov, .x.x.et.al. that could possibly work in all scenarios! There is no perfect solution, so I choose the minimalist thing and put the good input responsibility on the user.

I used regexp object (since I was reading up on regular expresssions):

myregexp = /[^\w@.-]/;

And then test for just those characters:

function checkEmail(){

document.getElementById('email').onblur = function(){
var input_value = document.getElementById("email").value;
if (myregexp.test(input_value)) {
alert("Please enter a valid email address to check!");

And then, to 'call' your function do:

window.onload = function(){

Notice the onblur event handler, instead of an element attribute radio or checkbox type; this way user only need alter the focus. Hope this helps.