In this article I’m going to explain how to
use RequiredFieldValidator control in ASP.NET.
RequiredFieldValidator
control:
The RequiredFieldValidator
control is used to make an
input control a required field. The validation fails if control doesn’t
contains any values. By default, the initial value is an empty string
("").
I’ve written few articles about
validation in ASP.NET. You may refer these articles too.
How to use CompareFieldValidator control in ASP.NET
How to use RangeValidator control in ASP.NET
How to use RegularExpressionValidator
control in ASP.NET
Here I’ll show you how to use RequiredFieldValidator
control. In this demo I’ve used two
TextBox controls will be validated by RequiredFieldValidator.
Properties:
ü ControlToValidate: Gets or sets the input control
to validate.
ü Display: Gets or sets the display
behavior of the error message in a validation control.
ü ErrorMessage: Gets or sets the text for the
error message displayed in a ValidationSummary control when validation fails.
ü SetFocusOnError: Gets or sets a value that
indicates whether focus is set to the control specified by the ControlToValidate property when validation fails.
ü ValidationGroup: Gets or sets the name of the
validation group to which this validation control belongs.
Designer
source code:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!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>Required
Filed Validator Demo</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table>
<tr>
<td>Name :
</td>
<td><asp:TextBox ID="txtName" runat="server" ValidationGroup="Submit" ></asp:TextBox>
</td>
<td>
<asp:RequiredFieldValidator ID="txtName_RequiredFieldValidator" runat="server"
ErrorMessage="Name
required" ValidationGroup="Submit"
ControlToValidate="txtName"
Display="Dynamic"
ForeColor="Red">
</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td>City :
</td>
<td><asp:TextBox ID="txtCity" runat="server" ValidationGroup="Submit" ></asp:TextBox>
</td>
<td>
<asp:RequiredFieldValidator ID="txtCity_RequiredFieldValidator" runat="server"
ErrorMessage="Age
required" ValidationGroup="Submit"
ControlToValidate="txtCity"
Display="Dynamic"
ForeColor="Red">
</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td colspan="3">
<asp:Button ID="btnSubmit" runat="server" Text="Submit" ValidationGroup="Submit"/></td>
</tr>
</table>
</div>
</form>
</body>
</html>