ASP.Net Code

ASP.Net – Validate postal/zip code based on Country

ASP.Net 2.0 comes with some powerful input validation controls. It's east to add a RequiredFieldValidator to a form, to ensure that the user inputs data of some sort. But what if you need data in a specific format? And what if that format changes? The example in this code uses a RegularExpressionValidator to check the proper format of a Zip code. However, if the user selects the country Canada, the regular expression changes to check for a valid postal code.

You can modify it, add as many countries & regular expressions as you'd like!


Country: <br />
<asp:DropDownList ID="ListCountry" runat="server" DataSourceID="DSCountries"
DataValueField="id" DataTextField="name" OnSelectedIndexChanged="ChangeCountry" AutoPostBack="true" />

<asp:SqlDataSource ID="DSCountries" runat="server" ConnectionString="<%$ ConnectionStrings:ConnString %>"
SelectCommand="SELECT [id], [name] FROM [countries] ORDER BY [name]" />

Zip/Postal Code: <br />
<asp:TextBox runat="server" ID="ZipCode" CssClass="text" />

<asp:RequiredFieldValidator runat="server" ID="ValZipCode" ControlToValidate="ZipCode" Display="Dynamic" 
ErrorMessage="Please specify the zip or postal code." />

<asp:RegularExpressionValidator ID="REXZipCode" runat="server" ControlToValidate="ZipCode" 
ErrorMessage="Zip/Postal code is invalid format" ValidationExpression="\d{5}(-\d{4})?" />

And here's the function that switches the regular expression for the chosen country. Note – the regular expression used to check the Canadian Postal code checks the format only; it does not verify that it is indeed a valid postal code!


protected void ChangeCountry(object s, EventArgs e)
{
	switch (ListCountry.SelectedItem.Text.ToLower())
	{
	  case "canada":
		REXZipCode.ValidationExpression = "[A-Z]\\d[A-Z] \\d[A-Z]\\d";
		break;
	  case "us":
		REXZipCode.ValidationExpression = "\\d{5}(-\\d{4})?";
		break;
	}
}
Share

1 Comments

  1. This code does the page postback… i would like to do the same funcntionality in client i.e using javascript? is it possible?

    ~Ram

Leave a Reply

Your email address will not be published. Required fields are marked *

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Anti-spam image