15 February 2014

Required Field Validator-asp.net

       Required Field Validator control in ASP.NET is a simple validator which checks to see if the data is entered for the attached control. You can set the Error Message property which you want to display. The another property is Control To Validate in which you can set the attached control 
instance

Implementation of Required Field Valdiator in Asp.net:

          We will also add a Text Box to validate, as well as a button to submit the form with.

         <form id="form1" runat="server">Your name:<br />
         <asp:TextBox runat="server" id="txtName" />
         <asp:RequiredFieldValidator runat="server" id="reqName" controltovalidate="txtName"         errormessage="Please enter your name!" />
         <asp:Button runat="server" id="btnSubmitForm" text="Ok" />
        </form>

            Actually, that's all we need to test the most basic part of the RequiredFieldValidator. I'm sure that all the attributes of the controls makes sense by now, so I won't go into details about them.The button does nothing, besides posting back if the page is valid. We will change this by adding an onclick event to it:

<asp:Button runat="server" id="btnSubmitForm" text="Ok" onclick="btnSubmitForm_Click" />

In the CodeBehind file, we add the following event handler:

protected void btnSubmitForm_Click(object sender, EventArgs e)
{
      if(Page.IsValid)
       {
        btnSubmitForm.Text = "My form is valid!";
       }

We check whether or not the page is valid, before we do anything.

No comments:

Post a Comment