RegularExpressionValidator in ASP.NET

RegularExpressionValidator validation control in ASP.NET validates a control according to the regular expression (RegEx) set to its ValidationExpression property. Using this validation control we can specify a format of data that a control should accept using a RegEx. For example, we can validate a Phone number, Email, Zip Code etc using a RegularExpressionValidator control.

Properties of RegularExpressionValidator control

Property Uses
ControlToValidate Gets or sets ID of the input control to validate
ValidationExpression Gets or sets the regular expression that specifies the pattern used to validate the input control
ErrorMessage Gets or sets the error message displayed when validation fails

Example 1: Validating an Email using RegularExpressionValidator

<asp:TextBox
     ID="txtEmail"
      runat="server"
      CssClass="textbox">
</asp:TextBox>

<asp:RegularExpressionValidator
     ID="revEmail"
     runat="server"
     ControlToValidate="txtEmail"
     ValidationExpression="w+([-+.']w+)*@w+([-.]w+)*.w+([-.]w+)*"
     ErrorMessage="(Invalid Email)"
     ForeColor="Red">
 </asp:RegularExpressionValidator>

Example 2: Validating an URL using RegularExpressionValidator

<asp:TextBox
     ID="txtURL"
     runat="server"
     CssClass="textbox">
</asp:TextBox>

<asp:RegularExpressionValidator
     ID="revURL"
     runat="server"
     ControlToValidate="txtURL"
     ErrorMessage="(Invalid URL)"
     ForeColor="Red"
     ValidationExpression="http(s)?://([w-]+.)+[w-]+(/[w- ./?%&=]*)?">
</asp:RegularExpressionValidator>

Note: RegularExpressionValidator does not apply on blank fields like other validation controls. Therefore you should use a RequiredFieldValidator with a RegularExpressionValidator to validate blank fields.

RegularExpressionValidator comes with some predefined regular expressions that can be accessed from its property window. To access these sample regular expressions, select the RegularExpressionValidator in the design view and click the ellipses(…) next to the ValidationExpression property in the property window. It will open Regular Expression Editor with regular expressions to select

RegularExpressionValidator propertiesRegular Expression Editor

Leave a Reply

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