Wednesday, July 1, 2009

Javascript E-Mail Validation

Try testing the following form with valid and invalid email addresses. The code uses javascript to match the users input with a regular expression.

The Code
function validate(form_id,email) {
var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
var address = document.forms[form_id].elements[email].value;
if(reg.test(address) == false) {
alert('Invalid Email Address');
return false;
}
}


Design
In the forms 'onsubmit' code call javascript:return validate('form_id','email_field_id')

<form id="form_id" method="post" action="action.php" onsubmit="javascript:return validate('form_id','email');">
<input type="text" id="email" name="email" />
<input type="submit" value="Submit" />
</form>

Source : http://www.white-hat-web-design.co.uk/articles/js-validation.php

No comments:

Post a Comment