Search This Blog

Saturday, August 28, 2010

IsValidEMail-Check Onblur

Rather than hard-coding your JavaScript into an aspx page, you can store you JavaScript functions in a separate .js file. This allows your furnctions to be used from multiple pages.

For example, you could add a .js file to your project (right-click your project and select Add New Item | JScript File) from the shortcut menu) and place the following function in it:

function isValidEmail(emailAddressControl)


var emailPat = /^(\".*\"|[A-Za-z]\w*)@(\[\d{1,3}(\.\d{1,3}){3}]|[A-Za-z]\w*(\.[A-Za-z]\w*)+)$/;

var emailid = emailAddressControl.value;

var matchArray = emailid.match(emailPat);

if (matchArray == null) {

alert("Invalid e-mail address");


return false;


return true;


In your web form Page_Load, you can add the following code

if (!Page.ClientScript.IsClientScriptIncludeRegistered(typeof(pgOrders), "MyScript"))


Page.ClientScript.RegisterClientScriptInclude(typeof(pgOrders), "MyScript", "JScript.js");


The call to IsClientScriptIncludeRegistered() checks if the JavaScript file has already been included. The call to RegisterClientScriptInclude() actually registers the script.

From within your .aspx page, you can call this JavaScript function after the user leaves the e-mail field by doing something like this:

<asp:TextBox ID="txtEmail" runat="server" Width="265px" onblur="isValidEmail(this)"></asp:TextBox>

Note: The first parameter of RegisterClientScriptInclude() accepts a type object which it uses to uniquely key the registered script. The MSDN documentation samples for this method use a call to this.GetType() to get the current page type dynamically at runtime--however, this can be a problem if you ever subclass your web page. The call to this.GetType() will return a different class than the class in which this code is actually defined. I's best to specify the actual type of the page itself by doing something like this:


In this example, pgOrders is the actual type of the page in which the JavaScript is being included. This works better, because you are statically typing the reference to the page at compile time rather than dynamically determining the type of the page at runtime.

No comments:

Post a Comment