loads of useful information, examples and tutorials pertaining to web development utilizing asp.net, c#, vb, css, xhtml, javascript, sql, xml, ajax and everything else...

 



Advertise Here
C-Sharpener.com - Programming is Easy!  Learn Asp.Net & C# in just days, Guaranteed!

Common Asp.Net Regular Expression Validators

by naspinski 1/29/2009 5:04:00 AM

Some of my most commonly used RegularExpressionValidators

Regular Expressions (regexs) are infinitely uesful in validation, but they can be a pain in the butt. With constant help from two amazing websites: RegExLib to find regexs and regexpal to test my own I have been able to put together some of my most commonly users validators.

Email Address

<asp:RegularExpressionValidator ID="regEmail" runat="server"
  ControlToValidate="someTextBox" ErrorMessage="invalid email"
  ValidationExpression="^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$" />

Phone Number

<asp:RegularExpressionValidator ID="regPhone" runat="server"
  ControlToValidate="someTextBox" ErrorMessage="invalid phone"
  ValidationExpression="^(\+[1-9][0-9]*(\([0-9]*\)|-[0-9]*-))?[0]?[1-9][0-9\- ]*$" />

Zip Code

<asp:RegularExpressionValidator ID="regZip" runat="server"
  ControlToValidate="someTextBox" ErrorMessage="invalid zip"
  ValidationExpression="^\d{5}((-|\s)?\d{4})?$" />

Password Length (just change the 8's to your desired value)

<asp:RegularExpressionValidator ID="regPwLength" runat="server"
  ControlToValidate="someTextBox" ErrorMessage="too short"
  ValidationExpression="^.{8}.*$" />

Date

<asp:CompareValidator ID="cvDate" runat="server"
  ControlToValidate="someTextBox" ErrorMessage="invalid date"
  Operator="DataTypeCheck" Type="Date" />

If you noticed, for date it is CompareValidator - why reinvent the wheel?

Related posts


Comments are closed