Kwizcom Forms

Asp.Net Validation Controls

Asp.Net Validation Controls

In asp.net, we use validation controls to validate user input data in asp.net forms with controls. So that user cannot enter malicious data easily. Asp.Net validation controls provides validation at server side as well as at client side.

We will also discuss various asp.net controls validation examples.

SharePoint deveopment training course

Asp.Net validation controls

Asp.Net provides below 6 type of validation controls to use. These are

  • Requiredfield validator
  • Range validator
  • Compare validator
  • RegularExpression validator
  • Validation Summary
  • Custom validator

Required Field Validation Control in Asp.Net

Now, we will see how to use Required Field Validation control in Asp.Net to validate user input.

RequiredFieldValidator will show an error message if a user tries to submit without entering a value in the field. To use RequiredFieldValidator, drag and drop a RequiredFieldValidator from Toolbox.

Here ControlToValidate property field needs to be set as on which field you want to validate. And ErrorMessage property will show whatever error message you will give.

Below is the full HTML code

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ValidatorExamples.aspx.cs" Inherits="ValidatorExamples" %>

<!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>RequiredFieldValidator example in Asp.Net</title>
</head>
<body>
<form id="form1″ runat="server">
<div>
Enter First Name:<asp:TextBox ID="txtFirstName" runat="server"></asp:TextBox><br />
<asp:RequiredFieldValidator ID="RequiredFieldValidator1″ runat="server" ForeColor="Red" ErrorMessage="Enter First Name!" ControlToValidate="txtFirstName"></asp:RequiredFieldValidator><br />
<asp:Button ID="btnSubmit" runat="server" Text="Submit" />
</div>
</form>
</body>
</html>

If the user tries to submit enter without filling any value in the Textbox then you will get the error message as shown in the figure below:

asp.net required field validator
asp.net required field validator

Range Validation Control in Asp.Net

Now, we will see an example of how to use Range Validator control in Asp.Net.

Here validation succeeds if the input control contains a value within a specific numeric, alphabetic, or date range.

To use Range Validator control, drag and drop a Range Validation control from Toolbox.

Below are the property need to set:

  • ControlToValidate: This property field needs to be set as on which field you want to validate.
  • ErrorMessage: This property will show whatever error message you will give.
  • MaximumValue: Indicates what will be the maximum value allowed.
  • MinimumValue: Indicates what will be the minimum value allowed.
  • Type: Indicates what will be the type. The value can be Integer, Currency, Date, Double or String.

Below is the full HTML code

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ValidatorExamples.aspx.cs" Inherits="ValidatorExamples" %>

<!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>RangeValidator example in Asp.Net</title>
</head>
<body>
<form id="form1" runat="server">
<div>
Enter Age:<asp:TextBox ID="txtAge" runat="server"></asp:TextBox>
<br />
<asp:RangeValidator ID="RangeValidator1″ runat="server" ErrorMessage="Age should be between 10 to 90!" ForeColor="Red" ControlToValidate="txtAge" MaximumValue="90″ MinimumValue="10" Type="Integer"></asp:RangeValidator>
<br />
<asp:Button ID="btnSubmit" runat="server" Text="Submit" />
</div>
</form>
</body>
</html>

If you try to submit enter any value in the Textbox which is not between the minimum value and maximum value set then you will get the error message as shown in the figure below:

Range Validation Control in Asp.Net
Range Validation Control in Asp.Net

Asp.Net compare validator

This example, we will see how to use compare validation control in Asp.Net.

Here in this example, we will take 2 textboxes on for start serial number and another one is the end serial number. And our validation will start serial number should be smaller than the end serial number. Below is the full code:

<head runat="server">
<title>Compare validator example in asp.net</title>
</head>
<body>
<form id="form1" runat="server">
<div>
Start Serial Number:
<asp:TextBox ID="txtSerialFrom" runat="server"></asp:TextBox><br />
End Serial Number:
<asp:TextBox ID="txtSerialTo" runat="server"></asp:TextBox><br />
<asp:CompareValidator ID="CompareValidator1" runat="server" ErrorMessage="End Serial number should be greater than start serial number" ControlToValidate="txtSerialTo" ControlToCompare="txtSerialFrom" Type="Integer" Operator="GreaterThan" ValidationGroup="Group1" ForeColor="Red">
</asp:CompareValidator><br />
<asp:Button ID="btnCheck" runat="server" Text="Check" ValidationGroup="Group1" />
</div>
</form>
</body>

Here the property Operator will take values such as: GreaterThan, Equal, DataTypeCheck, GreaterThanEqual, LessThan, LessThanEqual, NotEqual.

And you can use compare validator for Currency, Date, Double, Integer and String which is set in the Type property.

If you will enter a higher value in the first textbox than the value in the 2nd textbox the error message will appear

Regular Expression Validator in Asp.Net

Now, let us see how to use RegularExpressionValidator in Asp.Net. For this example we will see how to validate email id using RegularExpressionValidator in Asp.Net.

In asp.net Regular Expression Validator, validation succeeds if the value in an input control matches a specified regular expression.

Below are the properties we need to fill for asp.net regular expression validation control

  • ControlToValidate: Which control you want to validate.
  • ErrorMessage: What error message you want to show.
  • ValidationExpression: This represents the validation expression you want to validate. You can directly set the validation expression or Asp.Net provides some validation expressions which you can select from RegularExpressionValidator’s properties window.

Below is the full HTML code:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ValidatorExamples.aspx.cs" Inherits="ValidatorExamples" %>

<!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>RegularExpressionValidator example in Asp.Net</title>
</head>
<body>
<form id="form1" runat="server">
<div>
Enter EmailID:<asp:TextBox ID="txtEmailID" runat="server"></asp:TextBox>
<br />
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ForeColor="Red"
ControlToValidate="txtEmailID" ErrorMessage="Please enter a valid email id" ValidationExpression="\w+([-+.’]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"></asp:RegularExpressionValidator>
<br />
<asp:Button ID="btnSubmit" runat="server" Text="Submit" />
</div>
</form>
</body>
</html>

If a user enters a invalid email id then the error will be shown as shown in the figure below:

Regular Expression Validator in Asp.Net
Regular Expression Validator in Asp.Net

Validation Summary Control in asp.net

Now we will see how to use validation summery control in asp.net.

Validation Summary shows all the validation messages as summery in asp.net.

Check out the full code here:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ValidatorExamples.aspx.cs" Inherits="ValidatorExamples" %>

<!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>RegularExpressionValidator example in Asp.Net</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ValidationSummary ID="ValidationSummary1″ runat="server" ShowMessageBox="false" ShowSummary="true" ForeColor="Red" />
Enter First Name:<asp:TextBox ID="txtFirstName" runat="server"></asp:TextBox><br />
<asp:RequiredFieldValidator ID="RequiredFieldValidator1″ runat="server" ForeColor="Red"
ErrorMessage="Enter First Name!" ControlToValidate="txtFirstName" Text="*"></asp:RequiredFieldValidator><br />
Enter EmailID:<asp:TextBox ID="txtEmailID" runat="server"></asp:TextBox>
<br />
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ForeColor="Red" ErrorMessage="Enter Email ID!" ControlToValidate="txtEmailID" Text="*"></asp:RequiredFieldValidator><br />
<br />
<asp:Button ID="btnSubmit" runat="server" Text="Submit" />
</div>
</form>
</body>
</html>

Here the main properties are:

ShowMessageBox:
If ShowMessageBox is true then the error message will show in a Dialog box like below:

Validation Summary Control in asp.net
Validation Summary Control in asp.net

ShowSummary:
If ShowSummary is True then the error message will show as summery like below:

asp.net validation summery control
asp.net validation summery control

Allow only numeric values into textbox in Asp.Net using regular expression validator

Now, we will see how to use regular expression validator to the textbox that will allow only numeric values into the textbox in Asp.Net.

Through regular expression, you can allow the user to enter only numeric values into the textbox.

The regular expression is “\d+”.

Below is the full code:

<div>
Enter Number:
<asp:TextBox ID="txtNumber" runat="server"></asp:TextBox><br />
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ControlToValidate="txtNumber" ErrorMessage="Please enter only numeric value" ValidationExpression="\d+" ForeColor="Red"></asp:RegularExpressionValidator>
<br />
<asp:Button ID="btnSumbmit" runat="server" Text="Submit" />
</div>

Check the below fig, here user wanted to enter a letter and it shows the error message.

Allow only numeric values into textbox in Asp.Net
Allow only numeric values into textbox in Asp.Net

Below is the fig where the user put a number and it did not show any error message.

Allow only numeric values into textbox in Asp.Net using regular expression validator
Allow only numeric values into textbox in Asp.Net using regular expression validator

This ways we can restrict user to enter only numeric values in asp.net.

Validation Group example in Asp.Net

Here we will see how to use Validation Group in Asp.Net with asp.net validation controls.

If your page has several groups of controls and you want to perform validation separately then ValidationGroup will be very much helpful.

You have to assign ValidationGroup to controls, validators, and buttons. Here in this example, we have two panels.

Below is the .aspx code:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ValidatorExamples.aspx.cs" Inherits="ValidatorExamples" %>

<!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>ValidationGroup example in Asp.Net</title>
</head>
<body>
<form id="form1″ runat="server">
<div>
<asp:Panel ID="pnlLogin" runat="server">
Enter EmailID:<asp:TextBox ID="txtEmailIDLogin" runat="server" ValidationGroup="Group1″></asp:TextBox><br />
<asp:RequiredFieldValidator ID="RequiredFieldValidator1″ runat="server" ForeColor="Red"
ValidationGroup="Group1″ ErrorMessage="Enter Email ID!" ControlToValidate="txtEmailIDLogin"></asp:RequiredFieldValidator><br />
<asp:Button ID="btnLogin" runat="server" Text="Submit" ValidationGroup="Group1″ />
</asp:Panel>
<asp:Panel ID="pnlSignup" runat="server">
Enter EmailID: <asp:TextBox ID="txtEmailIDSignUp" runat="server" ValidationGroup="Group2″> </asp:TextBox>
<br />
<asp:RequiredFieldValidator ID="RequiredFieldValidator2″ runat="server" ForeColor="Red" ErrorMessage="Enter Email ID!" ControlToValidate="txtEmailIDSignUp" ValidationGroup="Group2″></asp:RequiredFieldValidator>
<br />
<asp:Button ID="btnSignup" runat="server" Text="Submit" ValidationGroup="Group2″/>
</asp:Panel>
</div>
</form>
</body>
</html>

Here if you click on the first button then only 1st textbox will get validated. And also if you click on the second button then 2nd textbox will get validated like the below figure.

Validation Group example in Asp.Net
Validation Group example in Asp.Net

Validate URL using regular expression in Asp.Net

We will discuss how we can validate an URL (both HTTP and https) using regular expression validator in Asp.net.

Through regular expression, we can validate an internet URL address in asp.net. The validation expression for this is:

"http(s)?://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?"

This will validate both http and https urls in asp.net. Below is the full aspx code:

<div>
Enter URL:
<asp:TextBox ID="txtURL" runat="server"></asp:TextBox><asp:RegularExpressionValidator ID="RegularExpressionValidator1″ runat="server"
ControlToValidate="txtURL" ErrorMessage="Enter a valid URL" ForeColor="Red" ValidationExpression="http(s)?://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?"></asp:RegularExpressionValidator>
<br />
<asp:Button ID="btnSubmitURL" runat="server" Text="Submit URL" />
</div>

If you will not put a valid url then the error will come like below:

Validate URL using regular expression in Asp.Net
Validate URL using regular expression in Asp.Net

Set Maximum length for multiline textbox in asp.net using regular expression validator

In this example, we will discuss how to set a maximum length for multiline textbox in asp.net using regular expression validator.

To make a textbox as multiline textbox we need to add the property as TextMode=”MultiLine”.

In case of Single line textbox, you can set the maximum length by setting a value for the property as MaxLength as MaxLength=”10″.

For multiline of textbox we can use a regular expression and the regular expression will be: ValidationExpression=”^[\s\S]{0,20}$”

.Aspx Code:
<div>
            Text:
            <asp:TextBox ID="txtMultiline" runat="server" TextMode="MultiLine" Height="69px" Width="302px"></asp:TextBox><br />
            <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ValidationExpression="^[\s\S]{0,20}$" ErrorMessage="Can not enter more than 20 characters" ForeColor="Red" ControlToValidate="txtMultiline"></asp:RegularExpressionValidator>
        </div>

Once you will set the regular expression, if you put more than 20 characters, it will appear like below:

Validate multiline textbox in Asp.net
Validate multiline textbox in Asp.net

Validate multiline textbox in Asp.net using JavaScript

Now. we will see, how to set maximum length for multiline textbox in Asp.net using JavaScript function.

To do this first we need to write the JavaScript function like this:

<script type=”text/javascript”>
        function CheckCharacters(textBox, maxLength) {
            if (textBox.value.length > maxLength) {
                alert(“Maximum  ” + maxLength + ” characters allowed.”);
                textBox.value = textBox.value.substr(0, maxLength);
            }
        }
</script>

Then we need to call the JavaScript function in onkeyup and onchange event like below:

<asp:textbox id="txtDescription" runat="server" textmode="MultiLine" onkeyup="javascript:CheckCharacters(this, 20);" onchange="javascript:CheckCharacters(this, 20);"></asp:textbox>

So when user try to enter characters, and when character count greater than 20 then it will show the alert message like below:

Validate multiline textbox in Asp.net using JavaScript
Validate multiline textbox in Asp.net using JavaScript

Regular expression validator for image files in Asp.Net

In this example, we will see how to use the regular expression validator to validate image files in Asp.net.

By using the regular expression you can check whether a user is trying to upload a valid image file or not. Here we have taken a file upload control, a regular expression validator, and a button.

The valid regular expression is: “^.*.((j|J)(p|P)(e|E)?(g|G)|(g|G)(i|I)(f|F)|(p|P)(n|N)(g|G))$”

Below is the full code:

<div>
<asp:FileUpload ID="FileUpload1″ runat="server" Width="449px" /><br />
<asp:RegularExpressionValidator ID="RegularExpressionValidator1″ runat="server"
ErrorMessage="Please enter a valid image file" ControlToValidate="FileUpload1″ ForeColor="#FF3300″
ValidationExpression="^.*\.((j|J)(p|P)(e|E)?(g|G)|(g|G)(i|I)(f|F)|(p|P)(n|N)(gG))$"></asp:RegularExpressionValidator>
<br />
<asp:Button ID="btnUpload" runat="server" Text="Upload" />
</div>

Here check the figure below, in the below fig i tried to upload an docx file and it is showing me the validation message.

validate image files in Asp.net
validate image files in Asp.net

Which validation should we prefer? jQuery or Asp.Net validation controls

Let us discuss, which type of validation we should use in our Asp.Net applications. Whether we should use jQuery or JavaScript validation or we should use our inbuilt Asp.Net validation controls?

It depends on how rich client you want to build and It’s entirely a performance optimization. A client validation (jQuery/javascript) failure saves a round trip to your server, helping to scale and allowing to reduce the response time for users. But some cases validation work must take place server-side (For example : Date Validation).

If you want to make a secure application, validation has to be done on both sides, client and server. Remember the client side, especially javascript can always be hacked from the browsers by a user.

Also, it depends on how much control you have over the entire page content. JavaScript can not only be hacked but easily broken by content that another developer or dynamic content adds to the page. In addition, JQuery is still seen as a technical skill that many web developers do not possess (unfortunately) which will make it more difficult to maintain.

ASP.Net validation controls help you automate the server-side validation and keep it in sync with the client, while jQuery still requires you to write the server-side logic separately.

ASP.Net validation controls help you automate the server-side validation and keep it in sync with the client, while jQuery still requires you to write the server-side logic separately.

Validation should be done on the client side and server side for added security, protecting the application from undesired data. Some in this forum think that JQuery is a skill or its hard.

To simply put it, JQuery is a framework that has been around a few years, and it wraps DOM object manipulation that is browser safe. JQuery’s biggest challenge is the selector, once you master that, you are ready to take on the world.

You may like following asp.net tutorials:

Hope this asp.net tutorial explains, asp.net validation controls. How to use required field validator, regular expression validator, range validator, compare validation controls. Also, we check how to use validation group in asp.net and how to use validation summery control in asp.net.

Check out Best Alternative to InfoPath -> Try Now

free sharepoint training

SharePoint Online FREE Training

JOIN a FREE SharePoint Video Course (3 Part Video Series)

envelope
envelope

About Bijay Kumar

I am Bijay from Odisha, India. Currently working in my own venture TSInfo Technologies in Bangalore, India. I am Microsoft Office Servers and Services (SharePoint) MVP (5 times). I works in SharePoint 2016/2013/2010, SharePoint Online Office 365 etc. Check out My MVP Profile.. I also run popular SharePoint web site SharePointSky.com

View all posts by Bijay Kumar →