KB:
Validate an Email Address using Regular Expressions
SATURDAY, FEBRUARY 27, 2010
|
|
This article gives you a simple code snippet for validating an email textbox field using Regular Expressions. The javascript function is called on onblur event
of the textbox, and it will not allow the user to leave the textbox without entering a valid email address. This may look like a disturbing feature, but I have
added a simple check at beginning to skip this checkup if the field is blank.
The regular expression used here is
^[a-zA-Z][w.-]*[a-zA-Z0-9]@[a-zA-Z0-9][w.-]*[a-zA-Z0-9].[a-zA-Z][a-zA-Z.]*[a-zA-Z]$
You can test this regular expressing using the
Online Regular Expression Test Tool.
The onblur validation script for validation the email address is:
function blurEmailCheck(cc) {
if (cc.value == '')
return true;
var rex = /^[a-zA-Z][w.-]*[a-zA-Z0-9]@[a-zA-Z0-9][w.-]*[a-zA-Z0-9].[a-zA-Z][a-zA-Z.]*[a-zA-Z]$/
if (rex.test(cc.value)) {
return true;
}
alert('Email field format is invalid.');
cc.focus();
cc.select();
return false;
}
To implement this on a textbox, add the onblur attribute to the textbox with value as return blurEmailCheck(this);. ASP.NET 2.0
allows direct addition of html attributes into an ASP.NET control, but for earlier versions, you have to add the attribute by code.
<asp:TextBox runat="server" ID="TextBox1" Width="200px" MaxLength="50" onblur="return blurEmailCheck(this);">
TextBox1.Attributes.Add("onblur", "return blurEmailCheck(this);");