In this article we will learn how to use RegularExpressionValidator control in ASP. NET.
RegularExpressionValidator
RegularExpressionValidator control are used for pattern matching or RegularExpressionValidator validation control is used to make sure that a textbox will accept a predefined format of characters.
Properties:
These are the following properties of the RegularExpressionValidator control.
Figure 1.
ValidationExpression - Gets or sets the regular expression that will be used to validate input control data.
ControlToValidate - The id of the control to validate.
Display - The display behavior for the validation control. Legal values are:
-None (the control is not displayed. Used to show the error message only in the ValidationSummary control).
-Static (the control displays an error message if validation fails. Space is reserved on the page for the message even if the input passes validation.
-Dynamic (the control displays an error message if validation fails. Space is not reserved on the page for the message if the input passes validation.
ErrorMessage - The text to display in the ValidationSummary control when validation fails. Note: This text will also be displayed in the validation control if the Text property is not set.
ForeColor - The foreground color of the control.
For Example:
Drag two Label control, one TextBox control, one Button control. The form looks like this.
Figure 2.
select RegularExpressionValidator and set the properties of that control.
Now click on the source button of the design form.
<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="WebForm1.aspx.vb" Inherits="WebApplication33.WebForm1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="lblOutput" runat="server" Font-Names="Verdana" Font-Size="10pt"
Text="Enter a 5 digit zip code" />
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server"
ControlToValidate="TextBox1" Display="Static" Font-Names="verdana"
Font-Size="10pt" ValidationExpression="\d{6}">
Zip code must be 6 numeric digits
</asp:RegularExpressionValidator>
<br />
<br />
<asp:Button ID="Button1" runat="server" Text="Submit" />
<br />
<br />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</div>
</form>
</body>
</html>
Now double click on the Validate(button) and add the following code.
protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
If Page.IsPostBack Then
Label1.Text = "Your PIN code number is right"
End If
End Sub
Now save and run the application.
Figure 3.
Suppose we enter 7 digit code then it will show an error message.
Figure 4.
Suppose we enter 6 digit code then it will show an error message.
Figure 5.