---
title: "Validations on Asp.Net Control"  
description: "If we have some options but we have needed one of them or select one of them then we can use checkbox control. Let’s have a brief idea on working of c"  
author: "AVADHESH PATEL"  
published: 2012-08-03  
updated: 2019-03-11  
canonical: https://www.mindstick.com/articles/973/validations-on-asp-dot-net-control  
category: "asp.net"  
tags: ["asp.net"]  
reading_time: 8 minutes  

---

# Validations on Asp.Net Control

If we have some options but we have needed one of them or select one of them then we can use [checkbox control](https://www.mindstick.com/articles/291/how-should-use-checkbox-control-in-vb-dot-net). Let’s have a brief idea on working of checkbox control.

##### CustomValidator on CheckBox \

##### Let me tell you for your information RequiredFieldValidator doesn't works with

CheckBox control. So to accomplish this purpose we can use CustomValidator to

validate checkbox control.

#####

##### At client side

##### Here I have validated CheckBox control as must be checked CheckBox control

before going farther process using javascript function ‘ValidateCheckBox’.

#####

##### .aspx Code:

##### ```
 // ValidateCheckBox function check CheckBox control Checked or UnChecked  <script type = "text/javascript">        function ValidateCheckBox(sender, args) {            if (document.getElementById("<%=cbxIAgree.ClientID %>").checked == true) {                args.IsValid = true;            } else {                args.IsValid = false;            }        }    </script>          //asp CheckBox control<asp:CheckBox ID ="cbxIAgree" runat="server" Text="I Agree" AutoPostBack="true"/> //asp custom validator witch call ValidationCheckBox javascript function<asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="You must checked I Agree to continue." ClientValidationFunction = "ValidateCheckBox"></asp:CustomValidator>
```

At server side\

If browser’s JavaScript disable, in this case above example use at server side

##### .aspx Code:

```
//asp CheckBox control<asp:CheckBox ID ="cbxIAgree" runat="server" Text="I Agree" AutoPostBack="true"/> //asp custom validator witch call ValidationCheckBox javascript function<asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="You must checked 'I Agree' to continue." OnServerValidate="CheckBox"></asp:CustomValidator>
```

.cs Code:

```
 //CheckBox function call by CustomValidator’s event OnServerValidate  public void CheckBox(object o, ServerValidateEventArgs e)    {        if (cbxIAgree.Checked)            e.IsValid = true;        else            e.IsValid = false;    }
```

##### Validations for CheckBoxList in asp.net

The CheckBoxList control is used to create a multi-selection check box group. Each selectable item in a CheckBoxList control is defined by a ListItem element!

##### CustomValidator on CheckBoxList

You might know that RequiredFieldValidator doesn't works with CheckBoxList control. So to accomplish that purpose we can use CustomValidator to validate CheckBoxList.

##### At client side

Here I have validated CheckBoxList control as must be checked CheckBoxList control before going farther process using [JavaScript function](https://www.mindstick.com/forum/156513/asynchronous-javascript-function).

##### .aspx Code:

```
// ValidationCheckBoxList function, that check CheckBoxList checked or not  <script type="text/javascript">        function ValidateCheckBoxList(source, args) {            var chkListQualification = document.getElementById('<%= CheckBoxList1.ClientID %>');            var chkListinputs = chkListQualification.getElementsByTagName("input");            for (var i = 0; i < chkListinputs.length; i++) {                if (chkListinputs[i].checked) {                    args.IsValid = true;                    return;                }            }            args.IsValid = false;        }    </script> // asp CustomValidator<asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="Please select at least one qualification" ClientValidationFunction="ValidateCheckBoxList"></asp:CustomValidator> 
```

\

##### At server side

Here I have validated CheckBoxList control as must be checked CheckBoxList control befor going farther process using ServerValidateEvent

##### .aspx Code:

```
// asp CustomValidator<asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="Please select at least one qualification"  OnServerValidate="ValidateCheckBoxList"></asp:CustomValidator> 
```

.cs Code:

\

```
// ValidationCheckBoxLIst function call by CustomValidator event   public void ValidateCheckBoxList(object sender, ServerValidateEventArgs e)    {        int cnt = 0;         for (int i = 0; i < CheckBoxList1.Items.Count; i++)        {            if (CheckBoxList1.Items[i].Selected)            {                cnt++;            }             e.IsValid = (cnt == 0) ? false : true;        }    } 
```

\

##### Validations for DropDownList in asp.net

##### CustomValidator on DropDownList

Mostly developers facing problem, validating values in `DropdownList` control on client side to avoid costly **postback** and validate values on server side. There is a very simple solution to this problem. There is a very handy dandy `CustomValidator` control that can be used to validate any control on the page. There is one property of validator controls where lot of developers get stuck is `ControlToValidate`. This is where `CustomValidator` becomes handy. It does not require that property to be set. And that makes it very useful to validate not just one control but multiple control values.

We can use `CustomValidator at server side also.`

##### At client side

‘**CountryCheck’** javascript function force to select one of them item in **DropDownList** control using Client side event ‘**ClientValidatorFunction’** of CustomValidator control**.**

##### .aspx Code:

```
    <script type="text/javascript">         function CountryCheck(source, args)         {             var ddlCountry = document.getElementById ("<%=ddlCountry.ClientID%>");             var country = ddlCountry.options[ddlCountry.selectedIndex].value;             if (country == "0")             {                 args.IsValid = false;             }             else             {                 args.IsValid = true;             }         }    </script> <asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="Please Select Country." ControlToValidate=" DropDownList1" ClientValidationFunction="CountryCheck"></asp:CustomValidator>     <asp:Button ID="Button1" runat="server" Text="Submit" />
```

At server side\

‘SelectList function force to select one of them item in DropDownList control using server side event ‘OnServerValidate’ of CustomValidator control.

##### .aspx Code:

```
<asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="Plase Select
Country." ControlToValidate="ddlCountry"
    OnServerValidate="SelectList"></asp:CustomValidator>
     <asp:Button ID="Button1" runat="server" Text="Submit" />
```

##### .cs Code:

```
  public void SelectList(object sender, ServerValidateEventArgs e)    {        if (ddlCountry.SelectedIndex == 0)            e.IsValid = false;        else            e.IsValid = true;    }
```

CompareValidator on DropDownList

\

Through CompareValidator we can validate DropDownList as RequerFieldValidator

##### .aspx Code:

```
<asp:CompareValidator ID="CompareValidator1" runat="server" ControlToValidate="DropDownList1" ValueToCompare="0"         ErrorMessage="Field is required" Operator="NotEqual" ></asp:CompareValidator>
```

RequiredFieldValidator on DropDownList

\

RequiredFieldValidator is used to make mandatory field for selected item in DropDownList

##### .aspx Code:

```
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="Field is required" InitialValue="0" ControlToValidate="DropDownList1"></asp:RequiredFieldValidator>   
```

##### RangeValidator on DropDownList

RangeValidator proved facility to define limit of selected items.

##### .aspx Code:

```
 <asp:RangeValidator ID="RangeValidator1" runat="server" ErrorMessage="age between 18-28" MinimumValue="18" MaximumValue="28" Type="Integer" ControlToValidate="DropDownList1"></asp:RangeValidator>
```

##### Validations for FileUpload in asp.net

[FileUpload control](https://www.mindstick.com/articles/331/validating-fileupload-control-for-specific-file-type-and-required-field) is used for uploading file to the server from the client side.

##### For detailed reading about FileUpload visit:

[http://mindstick.com/Articles/c323d0d8-495e-46c6-a12d-024908aa7a29/](http://mindstick.com/Articles/c323d0d8-495e-46c6-a12d-024908aa7a29/)

[http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.fileupload.aspx](http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.fileupload.aspx)

##### RequiredFieldValidator on FileUpload

For validating for required field we have to use RequiredFieldValidator.

With this control, the [validation fails](https://www.mindstick.com/forum/34291/how-to-raise-a-callback-when-asp-dot-net-mvc-client-validation-fails) if the input value does not change from its initial value. By default, the initial value is an empty string ("").

For more details visit: [http://mindstick.com/Articles/34e5fb73-9bdf-4850-9a3e-e10a5f428148/](http://mindstick.com/Articles/34e5fb73-9bdf-4850-9a3e-e10a5f428148/)

##### .aspx Code:

```
     <asp:FileUpload ID="FileUpload1" runat="server" />         <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="RequiredFieldValidator" Text="*" ControlToValidate="FileUpload1"></asp:RequiredFieldValidator>
```

.cs Code:

\

```
  protected void Button1_Click(object sender, EventArgs e)    {        try        {            string filename = System.DateTime.Now.Date.Day.ToString() + System.DateTime.Now.Date.Second.ToString()+"_" + FileUpload1.PostedFile.FileName;            FileUpload1.SaveAs(Server.MapPath("document/") + filename);            ClientScript.RegisterClientScriptBlock(GetType(), "alert", "alert('File Upload Success')", true);        }        catch{}    }
```

CustomValidator on FileUpload\

\

[Custom Validation](https://www.mindstick.com/forum/160248/how-to-create-custom-data-annotations-for-custom-validation-on-model-property-in-dot-net-core) Control use at Server Side, Validation to check File Size before uploading

##### .aspx Code:

```
<asp:FileUpload ID="FileUpload1" runat="server"/>             <asp:CustomValidator ID="CustomValidator2" runat="server" ErrorMessage="FileSize should not exceed 20KB" ControlToValidate="FileUpload1"            OnServerValidate="checkfilesize"></asp:CustomValidator>         <asp:Button ID="Button1" runat="server" Text="Save" onclick="Button1_Click"/>
```

##### \

.cs Code:

```
    protected void checkfilesize(object source, ServerValidateEventArgs e)    {        string data = e.Value;        e.IsValid = false;        double filesize = FileUpload1.FileContent.Length;        if (filesize > 20580)        {            e.IsValid = false;        }        else        {            e.IsValid = true;        }    }     protected void Button1_Click(object sender, EventArgs e)    {        if (Page.IsValid)        {            string filename = System.DateTime.Now.Date.Day.ToString() + System.DateTime.Now.Date.Second.ToString() + "_" + FileUpload1.PostedFile.FileName;            FileUpload1.SaveAs(Server.MapPath("document/") + filename);            ClientScript.RegisterClientScriptBlock(GetType(), "alert", "alert('File Upload Success')", true);        }    }
```

RegularExpressionValidation on FileUpload

\
\

In this article I am going to explain how we can check and validate user for uploading only certain files and making uploading of file to be must for submission of form.

The RegularExpressionValidator control is used to ensure that an input value matches a specified pattern. The validation will not fail if the input control is empty. Use the RequiredFieldValidator control to make the field required.

For more details about RegularExpressionValidator visit following link:

http://www.mindstick.com/Articles/46ad6aee-13e6-4aad-a24a-268d20467f9f/?RegularExpressionValidator%20Control%20in%20ASP.Net

.aspx Code:

```
<asp:FileUpload ID="FileUpload1" runat="server" /> <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ErrorMessage="Only .doc , .docx or .txt files are allowed."ValidationExpression="^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))+(.doc|.docx|.txt)$"ControlToValidate="FileUpload1">*</asp:RegularExpressionValidator>
```

\

Here, [regular expression](https://www.mindstick.com/forum/65/regular-expression) for .doc, .docx, .txt files is:

"^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))+(.doc|.docx|.txt)$"

If you want some more or other files type to be uploaded then you can replace or add more extension with the above mentioned extensions.

##### Validations for RadioButton in asp.net

RadioButton controls are used when we need to make multiple sets of choices available, but we want the user to select only one of them. If they click on a second selection after making a first, the first selection is replaced by the second.

##### CustomValidator on RadioButton

If we want to make mandatory field for choosing RadioButton Control on webpage, for that we can use CustomValidator, because RequiredFieldValidator not support RadioButton Control. We can validate CustomValidator at client side and server side.

##### At client side

Here CustomeValidator is used at client side using JavaScript function ‘DirectionValidate’. That force to choose RadioButton control before going father task. Means here CustomValidator is used as RequiredFieldValidator.

##### .aspx Code:

```
<script language="javascript" type="text/javascript" >        function DirectionValidate(source,args){            if (document.getElementById("<%= RadioButton1.ClientID %>").checked ||document.getElementById("<%= RadioButton2.ClientID %>").checked)                args.IsValid = true;            else               args.IsValid = false;        }    </script> <asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="Choose one option" ClientValidationFunction="DirectionValidate"></asp:CustomValidator>
```

At server side

\

When browser’s javascript is disabling than above task we can perform at server side. That force to choose RadioButton control before going father task. Means here CustomValidator is used as RequiredFieldValidator.

##### .aspx Code:

```
<asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="Choose one option"  OnServerValidate="DirectionValidate"></asp:CustomValidator>
```

##### .cs Code:

```
protected void DirectionValidate(object source, ServerValidateEventArgs args)    {        args.IsValid= RadioButton1.Checked || RadioButton2.Checked;    }
```

##### Validations for RadioButtonList in asp.net

The ASP.NET **RadioButtonList** control is used to create a defined list of options in which a user can choose from.

##### RequiredFieldValidator on RadioButtonList

This asp control is used for selecting one of them item of RadioButtonList.

##### .aspx Code:

```
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="RequiredFieldValidator" ControlToValidate="RadioButtonList1"></asp:RequiredFieldValidator>
```

CustomValidator on RadioButtonList

##### At client side

Here CustomeValidator is used at client side using javascript function ‘ValidateRadioButtonList. That force to choose RadioButtonList control before going father task. Means here CustomValidator is used as RequiredFieldValidator.

##### .aspx Code:

```
<script language="javascript" type="text/javascript" >        function ValidateRadioButtonList(source, arguments) {            var RBL = document.getElementById("<%=RadioButtonList1.ClientID%>");            var radiobuttonlist = RBL.getElementsByTagName("input");            var counter = 0;            var atLeast = 1            for (var i = 0; i < radiobuttonlist.length; i++) {                if (radiobuttonlist[i].checked)                    counter++;            }            if (atLeast = counter)                arguments.IsValid = true;            else                arguments.IsValid = false;        }    </script> <asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="Choose one option" ClientValidationFunction="ValidateRadioButtonList"></asp:CustomValidator>
```

At server side

\

When browser’s javascript is disabling than above task we can perform at server side. That force to choose RadioButtonList control before going father task. Means here CustomValidator is used as RequiredFieldValidator.

##### .aspx Code:

```
<asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="Choose one option" OnServerValidate="ValidateRadioButtonList"></asp:CustomValidator>
```

##### .cs Code:

```
public void ValidateRadioButtonList(object sender,ServerValidateEventArgs e)    {        int counter = 0;        int atLeast = 1;        for (int i = 0; i < RadioButtonList1.Items.Count; i++)        {            if (RadioButtonList1.Items[i].Selected)                counter++;        }        if (atLeast == counter)            e.IsValid= true;        else            e.IsValid= false;    }
```

##### Validations for TextBox in asp.net

The TextBox control is used to create a text box where the user can input text.

##### RequiredFieldValidator on TextBox

The RequiredFieldValidator control is used to make an input control a required field.This control will display error message if the field on which validation control is applied is left blank.

##### .aspx Code:

```
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="RequiredFieldValidator" ControlToValidate="TextBox1">*</asp:RequiredFieldValidator>
```

##### RangeValidator on TextBox

The RangeValidator control is used to check that the user enters an input value that falls between two values. It is possible to check ranges within numbers, dates, and characters. Here I have checked integer value.

##### .aspx Code:

```
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> <asp:RangeValidator ID="RangeValidator1" runat="server" ErrorMessage="RangeValidator" ControlToValidate="TextBox1" MinimumValue="18" MaximumValue="28" Type="Integer" ToolTip="values
between 18-28">*</asp:RangeValidator>
```

##### CompareValidator on TextBox

The CompareValidator control is used to compare the value of one input control to the value of another input control or to a fixed value. Here I have compare two TextBox’s String.

##### .aspx Code:

```
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><asp:TextBox ID="TextBox2" runat="server"></asp:TextBox> <asp:comparevalidator ID="Comparevalidator1" runat="server" errormessage="CompareValidator" ControlToCompare="TextBox1" ControlToValidate="TextBox2" Type="String" ToolTip="String
not matched">*</asp:comparevalidator>
```

##### RegularExpressionValidator on TextBox

The RegularExpressionValidator control is used to ensure that an input value matches a specified pattern. Both server- and client-[side validation](https://www.mindstick.com/interview/33573/explain-client-and-server-side-validation) are performed unless the browser does not support client-side validation or the EnableClientScript property is set to false. Here I have checked internet email id formate.

##### .aspx Code:

```
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> <asp:RegularExpressionValidator            ID="RegularExpressionValidator1"            runat="server"            ErrorMessage="RegularExpressionValidator"            ControlToValidate="TextBox1"            ToolTip="Email id not in correct format"            ValidationExpression"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"</asp:RegularExpressionValidator>
```

CustomValidator on TextBox

\

The CustomValidator control allows you to write a method to handle the validation of the value entered.

##### At client side

##### .aspx Code:

```
<script type="text/javascript">        function stringlenth(source, argument) {            var txtValue = document.getElementById("TextBox1").value;            if (txtValue.length >= 8 && txtValue.length <= 16)                argument.IsValid = true;            else                argument.IsValid = false;        }    </script> <asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="CustomValidator" ClientValidationFunction="stringlenth" ToolTip="String Lengh between 8-16">*</asp:CustomValidator>
```

At server side\

##### .aspx Code:

```
<asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="CustomValidator" OnServerValidate="stringlenth" ToolTip="String Lengh between 8-16">*</asp:CustomValidator>
```

.cs Code:

```
public void stringlenth(object sender, ServerValidateEventArgs e)    {        if (TextBox1.Text.Length>= 8 && TextBox1.Text.Length <= 16)            e.IsValid= true;        else            e.IsValid= false;    }
```

---

Original Source: https://www.mindstick.com/articles/973/validations-on-asp-dot-net-control

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
