Share via


C#: Validation of required field in ASP.NET



Validating a required field is very important in ASP.NET. One of the ways to achieve that is by utilizing RequiredFieldValidator class. One of the examples of using it is in your cshtml file as part of a form is as follows:



      <form id=    "myform" runat="server">
                    Full name:<br />      
                    <asp:TextBox runat=      "server" id="fullName"  />  
                    <asp:              RequiredFieldValidator             runat=      "server" id="reqName"  controltovalidate="fullName"  errormessage="Please enter your full name!" />  
                    <br /><br />      
                    <asp:Button runat=      "server" id="submitFormBtn" text="Submit"  onclick="submitForm_Click"  />  
      </form>  
   
      protected void  submitForm_Click(object sender, EventArgs e)
      {  
                    if      (Page.IsValid)      
                    {      
                        btnSubmitForm.Text =       "This form is valid"      ;      
                    }      
      }  

More on RequiredFieldValidator class could be accessed from: /en-us/dotnet/api/system.web.ui.webcontrols.requiredfieldvalidator

Alternative approach using ASP.NET MVC


If you are using ASP.NET MVC programming for your project then the MVC is validating your model based on the type. In your model you can easily use the Required validation to check whether a field is required or not as follows:

public class  Book {
    public int  ID { get; set; }
 
    [Required(ErrorMessage="Title can not be empty")]
    public string  Title { get; set; }
 
    [Required(ErrorMessage="Author can not be empty")]
    public string  Author { get; set; }
 
    [DataType(DataType.Date)]
    public DateTime PublicationDate { get; set; }
}

In the aforementioned example, you can either use [Required] or [Required(ErrorMessage=``"Put your custom message here"``)] to show a custom message for the user.

More on adding validation to model in ASP.NET MVC can be accessed from here: /en-us/aspnet/mvc/overview/older-versions/getting-started-with-aspnet-mvc4/adding-validation-to-the-model