Introduction
ASP.NET is an open-source web framework that works on the server-side to produce dynamic web pages using HTML, CSS, JavaScript/ TypeScript. The ASP.NET supports the validation of the inputs given by the user. The technique we use for validation is REGEX. Let’s explore what REGEX is and how to use it.
ASP.NET REGEX
REGEX is a Regular expression that contains a sequence of the characters that specify the pattern of the text/ input given by the user. The validator analyses the input is given by the user and compares it with the pattern in REGEX, and accepts the input only if it matches the expected input format; otherwise, it gives out an error. It validates inputs like email, address, contact numbers, etc.
We use the ValidationExpression property in HTML to specify the REGEX for validation. Let’s learn how to write code for the validation of email.
<%@ Page AutoEventWireup="true" CodeBehind="RegularExpressionDemo.aspx.cs" Inherits="asp.netexample.RegularExpressionDemo" %>
<!DOCTYPE html>
<html>
<head runat="server">
</head>
<body>
<form id="form1" runat="server">
<div>
<table class="auto-style1">
<tr>
<td class="auto-style2">Email</td>
<td>
<asp:TextBox ID="email" runat="server"></asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ControlToValidate="email" ErrorMessage="Please enter a valid email" ForeColor="Red" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*">
</asp:RegularExpressionValidator>
</td>
</tr>
<tr>
<td class="auto-style2"></td>
<td>
<br/>
<asp:Button ID="Button1" runat="server" Text="Register"/>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
The ValidationExpression property specifies the REGEX we need to validate and email in the above code. It validates the email given in the text box using the ControlToValidate property. If the email is validated against REGEX, it accepts the input. Otherwise, it displays an error message, like shown in the picture below.
REGEX properties
Property | Description |
---|---|
AccessKey | used to set keyboard shortcuts for the control. |
BackColor | background-color property of the control. |
BorderColor | border-color property of the control. |
Font | property for the control text. |
ForeColor | color property of the control text. |
Visible | visibility of control on the form |
Text | used to set the text to be shown for control. |
ErrorMessage | error message that displays when validation fails. |
ToolTip | displays a text when the mouse is over the control. |
ControlToValidate | takes the ID of the control to validate. |
ValidationExpression | regular expression to determine validity. |
Height | height property of the control. |
Width | property of the control. |
Also read about .Net here.