ASP.Net RequiredFieldValidator Example, How to <asp:RequiredFieldValidator> Control make a mandatory field in asp.net c#

<asp:RequiredFieldValidator
id="ProgrammaticID"
ControlToValidate="ProgrammaticID of control to validate"
InitialValue="value"
ErrorMessage="Message to display in ValidationSummary control"
Text="Message to display in control"
ForeColor="value"
BackColor="value"
runat="server" >
</asp:RequiredFieldValidator>


Use the RequiredFieldValidator control to make an input control a mandatory field. The input control fails validation if the value it contains does not change from its initial value when validation is performed. This prevents the user from leaving the associated input control unchanged. By default, the initial value is an empty string (""), which indicates that a value must be entered in the input control for it to pass validation.

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

<!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>ASP.Net RequiredFieldValidator Example</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2 style="color:Red">RequiredFieldValidator</h2>
<asp:Label ID="lbl1Example" runat="server">
</asp:Label>
<br /><br />
<asp:Label ID="lbl2Example" runat="server">
</asp:Label>
<asp:TextBox ID="txtExample" runat="server">
</asp:TextBox>
<asp:RequiredFieldValidator
ID="RequiredFieldValidatorExample"
runat="server"
>
</asp:RequiredFieldValidator>
<br />
<asp:Button ID="ButtonExample" runat="server" Text="Submit" OnClick="ButtonExample_Click" />
</div>
</form>
</body>
</html>


using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class RequiredFieldValidator : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
lbl1Example.Font.Italic = true;
lbl1Example.ForeColor = System.Drawing.Color.SeaGreen;
lbl2Example.Text = "Name";
txtExample.ForeColor = System.Drawing.Color.SeaGreen;
ButtonExample.Font.Bold = true;
ButtonExample.ForeColor = System.Drawing.Color.SeaGreen;
RequiredFieldValidatorExample.ControlToValidate = "txtExample";
RequiredFieldValidatorExample.ErrorMessage = "input name!";
}
}

protected void ButtonExample_Click(object sender, EventArgs e) {
lbl1Example.Text = "Hello " + txtExample.Text.ToString();
}
}
Tags: ,
Hot on Web:


About author