Displaying Dynamic Error Message in ASP.NET Custom Validator Control

Introduction 
 
Generally we use an ASP.NET validation control to validate user input. Sometimes we use a custom validator control instead of other controls to implement our custom logic to validate user input. We use the ErrorMessage property to display the error message.
 
Assume you get a requirement to display the error message dynamically. Then it will not help to implement it directly (we need to implement it in code behind, not in the aspx page). So we need a way to display the dynamic error message.
 
It can be implemented in one of the following two ways:
 
   1. Using JavaScript
   2. Using OnServerValidate property
 
Let's start with how to implement a dynamic error message in an ASP.NET custom validator control.
 
Using JavaScript
 
Add a new aspx page to the project, then add an ASP TextBox and Button to the aspx page. Then add a CustomValidator Control to the aspx page by going to the ToolBox then under that click Validation, select CustomValidator, then drag it to the page.
 
Figure 1 shows how to add a custom validation control.
 
 
Figure 1: Add CustomValidator Control  
 
After adding the Custom control, add the property ClientValidationFunction to call the client-side JavaScript function for custom validation. Here's the code:
  1. <asp:TextBox ID="txtPhoneNumber" runat="server" Width="173px" />

  2. <asp:CustomValidator runat="server" Display="Dynamic" ID="customValidator1" ForeColor="Red"   ClientValidationFunction="ContactNumberValidation"  ErrorMessage="">  
  3. </asp:CustomValidator> 
  4.   
  5. <asp:Button ID="btnSave" runat="server" Text="Send Message" 
  6.  OnClick="btnSave_Click" ="True" ForeColor="#009933" /></td>  
  7.                  
Add the following JavaScript code to validate the user input. Here we can implement custom logic to validate and display the dynamic error message depending on requirements.
 
Code
  1. <script type="text/javascript">    
  2.    function ContactNumberValidation(sender, args) {    
  3.      if (document.getElementById("<%=txtPhoneNumber.ClientID %>").value == '') {    
  4.           sender.innerHTML = "Please enter your Phone Number.";    
  5.           args.IsValid = false;    
  6.      }else if (document.getElementById("<%=txtPhoneNumber.ClientID %>").value.length != 10) {    
  7.           sender.innerHTML = "Phone Number should be 10 digit.";    
  8.           args.IsValid = false;    
  9.      } else {    
  10.           args.IsValid = true;    
  11.      }    
  12.   }    
  13. </script>  
In the preceding code, the first if condition validates that the phone number is provided. It is checking the value by document.getElementById() to fetch the TextBox value. We set the sender.innerHTML value to display the error message and the args.IsValid property helps to check if the page is valid or not. If the end user doesn't enter a phone number then it displays the first error. Secondly, if the user provides a phone number (for example 93493) that is invalid then it displays the second error message.
 
Using OnServerValidate Property
 
Another option is to use a server-side method instead of client-side. Here we will use the OnServerValidate property in the Custom Control and we need to define the server method inside the code behind and implement our own logic to display the dynamic error message.
 
Let's start with how to implement an OnServerValidate property.
 
Step 1
 
Add a TextBox, Button and Custom Control as in the preceding section.
Once the controls have been added to the page we need to add an OnServerValidate property to the Custom Control. Here's the code:
  1. <asp:TextBox ID="txtPhoneNumber" runat="server" Width="173px" />  
  2.   
  3. <asp:CustomValidator runat="server" Display="Dynamic" ID="customValidator1"  
  4. ForeColor="Red" ErrorMessage="" OnServerValidate="customValidator_ServerValidate">  
  5. </asp:CustomValidator>  
  6.   
  7. <asp:Button ID="btnSave" runat="server" Text="Send Message"   
  8. OnClick="btnSave_Click""True" ForeColor="#009933" />  
Step 2
 
Add the following code to the code behind (aspx.cs) page: 
  1. protected void customValidator_ServerValidate(object source, ServerValidateEventArgs args)  
  2. {  
  3.     if (txtPhoneNumber.Text == string.Empty)  
  4.     {  
  5.         customValidator1.ErrorMessage = "Please enter your Mobile Number.";  
  6.         args.IsValid = false;  
  7.     }  
  8.     else if (txtPhoneNumber.Text.Length != 10)  
  9.     {  
  10.         customValidator1.ErrorMessage = "Phone Number should be 10 digit.";  
  11.         args.IsValid = false;  
  12.     }  
  13. }  
  14.   
  15. protected void btnSave_Click(object sender, EventArgs e)  
  16. {  
  17.     if (Page.IsValid)  
  18.     {  
  19.         // Implement your logic to perform action..  
  20.         SendMessage(txtPhoneNumber.Text);  
  21.     }  
  22. }  

In the preceding code we are checking whether the TextBox value is blank. If it is blank then it is setting an error message that it is required using the ErrorMessage property. Secondly, if the user provides an invalid phone number then it displays a second error message. Finally we set the IsValid property to false, that means the page is invalid. This helps when button click event fires. In the button click event we can check the Page.IsValid property to forward the process.

Once everything is implemented we need to browse the page to see the output. Figure 2 shows what it looks like when the page loads the first time. It doesn't display an error message.

 
Figure 2: Page loads first time with no error message
 
Figure 3 shows what it looks like when the user leaves the TextBox blank and hits the button. Here it displays an error message that it is required.
 
 
Figure 3: Error message when user don't provide mob number
 
Figure 4 shows what it looks like when the user provides an invalid number. It displays a different error message that the mobile number is invalid.
 
 
Figure 4: Error message when user don't writes invalid mobile number
 
Conclusion
 
This article showed two options to display an error message using a custom validator control. If it is required to implement it client-side, then option 1 (JavaScript) is the best. On the other hand if there is a requirement to implement it on the server side then option 2 (OnServerValidate) is the best. Choose depending on your requirements. 
 
In this way ASP.NET helps in displaying a dynamic error message in a Custom Control.
 
Happy Coding!


Similar Articles