Showing posts with label Validation. Show all posts
Showing posts with label Validation. Show all posts

Tuesday, March 4, 2014

How to use Regular Expression Validator for Textbox Control in ASP.NET

The Following example shows, how to use the Regular Expression Validator to validate the Textbox, it allows only numbers(integer values only).

I have a Textbox control called txtAge:

<asp:TextBox ID="txtAge" runat="server"></asp:TextBox>

Here I can use the Regular Expression in 2 methods.

Method 1: (Client Side validation)

<asp:RegularExpressionValidator ID="RegularExpressionValidator1"
runat="server" ControlToValidate="txtAge"
ErrorMessage="Enter Valid Age"
EnableClientScript="true"
ValidationExpression="\d+">
</asp:RegularExpressionValidator>

Exp: EnableClientScript="true", represents the client side validation.

Method 2: (Server Side validation)

<asp:RegularExpressionValidator ID="RegularExpressionValidator1"
runat="server" ControlToValidate="txtAge"
ErrorMessage="Enter Valid Age"
ValidationGroup="validate"
ValidationExpression="\d+">
</asp:RegularExpressionValidator>

Exp: ValidationGroup="validate", it will validate the textbox when a server side event hits. Like button click.

For that you have to use the button with the same validation group.

<asp:Button ID="btnSubmit" runat="server" Text="Submit" ValidationGroup="validate" />

From the above Regular Expression Validator, we have to mention the validation expression in ValidationExpression. Here I have used the Validation Expression as "\d+" which represents only numbers.

We can mention the Validation Expression as "\d{6}", it represents totally six digits should be entered in Age textbox. It's mainly used for Postal (Zip) code, age validation and etc.

Saturday, August 13, 2011

ASP.NET--Custom Validation Expression's

Some of the expression's that are used for validating the fields in the web form in ASP.NET

For Name:
^[a-zA-Z\s,.]{1-50}$

For Mobile Number:

^[7-9]{1}[0-9]{9}$

For Land-line Number:
^[0-9,\s,-]{10,13}$

For Car Registration Number:
^[a-zA-Z]{2}[0-9]{2}[a-zA-Z]{1,2}[0-9]{1,4}$

For E.mail:(Regular Expression)
\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*

For Website:
^((h|H?)(t|T?)(t|T?)(p|P?)(s|S?)\://)?(www.|[a-zA-Z0-9].)[a-zA-Z0-9\-\]+\.[a-zA-z]*$

Explanation:

^ and $                  -     For represents the Custom validation

a-z and A-Z            -     Letters from alphabets both upper and lower

0-9                        -     Numbers 0,1,2,3,4,5,6,7,8,9

\s (or) \S                -     Space between strings

{1,30} (or) {1,50}    -     Range or Count of the values. ex.  {min,max}

?                           -     For optional