How to Validate E-mail Addresses in javascript (javascript email validating)
Contributed by Joe
Friday, 21 July 2006
How to Validate E-mail Addresses in javascript (javascript email validating)
How to conform to a format of a valid email address, you should think about the following logic:
Syntax Check-Validates the address for syntax, whether it has all of the mandatory characters present (e.g. @) and any illegal characters present (i.e. ~). It will also check for multiple occurrences of required characters (i.e. @@).
DNS/MX Record Check-Validates the domain name with DNS server to ensure that the email domain is a valid registered domain.
Mail Server Check-Validates an email address (e.g.
) by mail server (e.g. mail.devx.biz) to ensure that the mail server indeed has the email address. This method has very good performance. (Attention: a few mail servers don't support this method(e.g. yahoo))
But to java script,we only can do Syntax Check-Validates,see ollowing logic:
Check if the e-mail address is empty; if it is, the field is not valid.
Check for illegal characters, and if they occur, the field is not valid.
Check if the @ symbol is missing; if it is, the field is not valid.
Check for the occurrence of a dot; if there is none, the field isn’t valid.
Otherwise, the field is valid.
Example of How to Validate E-mail Addresses in javascript
Create a function for validating an e-mail address.
function checkEmail(email) { if (email.length == 0) { window.alert(“You must provide an e-mail address.”); return false; } if (email.indexOf(“/”) > -1) { window.alert(“E-mail address has invalid character: /”); return false; } if (email.indexOf(“:”) > -1) { window.alert(“E-mail address has invalid character: :”); return false; } if (email.indexOf(“,”) > -1) { window.alert(“E-mail address has invalid character: ,”); return false; } if (email.indexOf(“;”) > -1) { window.alert(“E-mail address has invalid character: ;”); return false; } if (email.indexOf(“@”) < 0) { window.alert(“E-mail address is missing @”); return false; } if (email.indexOf(“\.”) < 0) { window.alert(“E-mail address is missing .”); return false; } return true; }
Create another function named checkForm
\It takes a form object as an argument. The function should call checkEmail and pass it the value of the field containing the e-mail address and then return the result returned by the checkEmail function:
function checkForm(formObj) { return checkEmail(formObj.myField.value); }
Create an email field
Create a form that contains a field for entering the e-mail address and uses the onSubmit event handler to call the checkForm function: