RequiredFieldValidator: This validation control will be used when a particular control should contain data while inserting into the database. For example, we are working on a user registration form, here username field is mandatory to be filled. In that case instead of validating the data in the code behind using the traditional if condition, RequiredFieldValidator fulfills our need.
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="Error Message" ControlToValidate="ControlID"></asp:RequiredFieldValidator>
Example:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="RequiredFieldvalidator.aspx.cs" Inherits="WebProgramming.Validators.RequiredFieldvalidator" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table>
<tr>
<td>
UserName: <asp:TextBox ID="txtUserName" runat="server"></asp:TextBox><asp:RequiredFieldValidator ID="rfcUsername" runat="server" ErrorMessage="UserName is required." ControlToValidate="txtUserName"></asp:RequiredFieldValidator></td>
</tr>
<tr>
<td>
<asp:Button ID="btnSubmit" runat="server" Text="Submit" /></td>
</tr>
</table>
</div>
</form>
</body>
</html>
Here rfcUsername is the Required field validator which monitors the value in txtUserName text box.
In case the user not supplied the data to the username field, it throws the error message as below.
No comments:
Post a Comment