The RequiredFieldValidator Server Control in asp.net


The RequiredFieldValidator Server Control

The RequiredFieldValidator control simply checks to see if something was entered into the HTML form element. It is a simple validation control, but it is one of the most frequently used. You must have a RequiredFieldValidator control for each form element on which you wish to enforce a value-required rule.

A simple use of the RequiredFieldValidator server control

<%@ Page Language="C#" %>
<script runat="server">
protected void Button1_Click(Object sender, EventArgs e)
{
Label1.Text = "Page is valid!";
}
</script><html xmlns="http://www.w3.org/1999/xhtml&quot; >
<head id="Head1" runat="server">
    <title>RequiredFieldValidator</title>
</head>
<body>
    <form id="form2" runat="server">
    <div>
        <asp:TextBox ID="TextBox1" Runat="server"></asp:TextBox>
        <asp:RequiredFieldValidator ID="RequiredFieldValidator1"
         Runat="server" ErrorMessage="Required!" ControlToValidate="TextBox1">
        </asp:RequiredFieldValidator>
        <br />
        <asp:Button ID="Button1" Runat="server" Text="Submit"
         OnClick="Button1_Click" />
        <br />
        <br />
        <asp:Label ID="Label1" Runat="server"></asp:Label>
    </div>
    </form>
</body>
</html>

Build and run this page. You are presented with a simple text box and button on the page. Don’t enter any value inside the text box, and click the Submit button.

The first property to look at is the ErrorMessage property. This property is the value that is shown to the end user via the Web page if the validation fails. In this case, it is a simple Required! string. The second property to look at is the ControlToValidate property. This property is used to make an association between this validation server control and the ASP.NET form element that requires the validation. In this case, the value specifies the only element in the form — the text box.

Other Related Posts:

Validations:

ASP.NET Validation Server Controls

The RequiredFieldValidator Server Control in asp.net

Validating Drop-Down Lists with the RequiredFieldValidator Control

The CompareValidator Server Control in asp.net

The RangeValidator Server Control in asp.net

The RegularExpressionValidator Server Control in asp.net

The CustomValidator Server Control in asp.net

The ValidationSummary Server Control in asp.net

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s