Monday, April 13, 2009

Calling validator controls from Javascript.

The series of blog discusses the following solutions.

In this blog we will see how to use javascript in conjunction with validator controls.

Calling ASP.NET validation controls using javascript

We all know when one clicks the submit button in ASP.NET page it triggers all the validation controls in the page without the developer writing a single line of code. The validation controls validates the controls associated with it and shows the appropriate error messages. But there may be situation where one wants to explicitly call the validators before doing a postback. So if you have a requirement where you want to call the validators manually in javascript and check whether everything is fine and then implement some custom validation logic before posting the page to the server then one can make use of the below techniques. Below is the sample HTML tag.

   1: <!--ASP.NET Drop down control--> 
   2:  
   3:  
   4: <asp:DropDownList ID="status" runat="server" Style="width: 100%"> 
   5:             <asp:ListItem Selected="True" Text="Select" Value="0"/> 
   6:             <asp:ListItem Text="One" /> 
   7:             <asp:ListItem Text="Two" /> 
   8:             <asp:ListItem Text="Three" />  
   9: </asp:DropDownList>
  10:  
  11: <!--ASP.NET Required Field Validator to validate the drop down.--> 
  12: <asp:RequiredFieldValidator ID="statusValidator" runat="server" ErrorMessage="Please choose a value other than 'Select'" ControlToValidate="status" InitialValue="0" Visible="true"> 
  13: </asp:RequiredFieldValidator> 
  14: <!--Validator callout control to show the error message in balloon tooltip--> 
  15: <ajaxtoolkit:ValidatorCalloutExtender ID="statusValCallout" runat="server" TargetControlID="statusValidator"> 
  16: </ajaxtoolkit:ValidatorCalloutExtender> 
  17:  
  18: <asp:Button ID="submit" Text="Submit" OnClientClick="javascript:return ValidatePage();" runat="server" /> 

From the above code one can see, we have a dropdown control, a RequiredFieldValidator attached to it and an ASP.NET AJAX ValidatorCalloutExtender control to show the error in a balloon tooltip. In the submit button’ OnClientClick event I am calling the user defined ValidatePage javascript function. The ValidatePage javascript function’ code is pasted below which calls the validation function of the validation control, validates the control attached to it and shows the validation error in the ValidatorCalloutExtender control.


   1: <script language="javascript" type="text/javascript"> 
   2: function ValidatePage() 
   3: { 
   4:     //Retrieving the validator control using the inline server side code. 
   5:     var valCntl = document.getElementById('<%=statusValidator.ClientID%>'); 
   6:     if (valCntl != undefined && valCntl != null)  
   7:     { 
   8:         //Method which takes a validator control as an argument and validates the control associated with it. 
   9:         ValidatorEnable(valCntl); 
  10:         // Or 
  11:         //ValidatorValidate(valCntl); 
  12:         //isvalid is a property in a validation control which says whether the validation was successful or not. 
  13:         if (valCntl.isvalid) 
  14:         { 
  15:             document.writeln('Page Successfully validated.'); 
  16:             return true; 
  17:         } 
  18:         else 
  19:         { 
  20:             document.writeln('Page not validated.'); 
  21:             return false; 
  22:         } 
  23:     } 
  24: } 
  25: </script>

The “ValidateEnable” is the ASP.NET generated javascript function which enables or disables a validation control and calls the validation logic associated with a validation control and shows the appropriate error messages if the validation fails. The method takes the validation control as an argument and internally calls ASP.NET generated “ValidatorValidate” method. The actual signature of the method is given below.


   1: ValidateEnable(ASP.NET validation Control, boolean)

The method takes an ASP.NET validation control as the first argument and a boolean value as the second argument. The boolean value decides whether to enable or disable the validation control. The method enables or disables the validation control and calls the validation logic associated with the ASP.NET validation control. If one puts a breakpoint at the ValidateEnable javascript code and steps into the function by pressing the F11 key one can see the below ASP.NET generated javascript code.


   1: function ValidatorEnable(val, enable) { 
   2:     val.enabled = (enable != false); 
   3:     ValidatorValidate(val); 
   4:     ValidatorUpdateIsValid(); 
   5: }

Internally the ValidatorEnable function calls ValidatorValidate method to validate a control after enabling or disabling the validation control.

If you want to only call the validation logic then you can call the ValidatorValidate function as shown below.


   1: ValidatorValidate(valCntl); 

ValidatorValidate takes the validation control as an argument and executes the validation logic and pops the error message in the ValidatorCallout control, if one is associated with the validation control, else it shows the error message as a text in the page or as a summary or as a javascript alert message.

If one wants to call the validation logic associated with an ASP.NET validation control one can make use of either ValidatorEnable or ValidatorValidate javascript function. These functions are auto created by the ASP.NET runtime. The major difference between these two methods are ValidatorValidate executes the validation logic associated with a validation control and shows the error on screen, if any, whereas ValidatorEnable enables or disables the validation control, then internally calls the ValidatorValidate method and finally calls ValidatorUpdateIsValid method which loops through all the validation controls in the page and sets the Page_IsValid variable to false, if any of the validation control’ validation logic fails.

Now you have called the function which will validate the validation control, next you want to check whether the validation logic associated with the validation control is successful or not. To check whether the validation was successful or not one can make use of the “isvalid” javascript property of the validation control as shown in the “ValidatePage” javascript function above.

Executing all the ASP.NET validation controls in a page using javascript.

The above solution is for firing the individual validation control’ validation logic from javascript, but there may be scenario where you don’t want to call each validation controls individually but would like to call/execute all the validation control’ validation logic in the page in a single shot. If you want to do just that then the below javascript code will help you in that.


   1: //Executes the validation logic of all the validation controls in a page. 
   2: if(Page_ClientValidate()) 
   3: { 
   4:  
   5:         alert(‘Page successfully validated’); 
   6: } 
   7: else 
   8: { 
   9:     alert(‘Page was not validated successfully.’); 
  10: }

Page_ClientValidate javascript function retrieves all the validation controls in the page, loops through each validation control and executes each validation control’ validation logic individually and returns a boolean value. The function returns false if any of the validation controls in the page fails to validate the control associated with it else returns true if all the validations were successful. With Page_ClientValidate javascript function one can execute all the validations in the ASP.NET page.

If at any point of time you want to check whether the page is having any validation error then you can make use of “Page_IsValid” javascript global variable. This javascript variable will have a false value if any of the validation control fails to validate the control associated with it. Sample code is given below.


   1: //Javascript variable which says whether the page is validated or not. True means success. 
   2: if(Page_IsValid) 
   3: { 
   4:       //Code to post back the page. 
   5: } 
   6: else 
   7: { 
   8:       alert('Failure'); 
   9: } 

Accessing all ASP.NET Validation controls in a page through javascript

One can access the individual ASP.NET validation control through javascript as shown above. If you want to retrieve all the ASP.NET validation controls in a page then one can make use of “Page_Validators” array collection object in javascript as shown below.


   1: //Page_Validators is an array of validation controls in the page. 
   2: if (Page_Validators != undefined && Page_Validators != null) 
   3: { 
   4:     //Looping through the whole validation collection. 
   5:     for(var i=0; i<Page_Validators.length; i++) 
   6:     { 
   7:         ValidatorEnable(Page_Validators[i]); 
   8:         //if condition to check whether the validation was successfull or not. 
   9:         if (!Page_Validators[i].isvalid) 
  10:         { 
  11:             break; 
  12:         } 
  13:     } 
  14: }
  15:  
  16: //if condition to check whether the page was validated successfully. 
  17: if(Page_IsValid) 
  18: { 
  19:     alert('Success'); 
  20: } 
  21: else 
  22: { 
  23:     alert('Failure'); 
  24: }

Page_Validators is a javascript array which holds all the ASP.NET validation controls in a page. In the above e.g. we are making use of the Page_Validators array and looping through each one and passing the validation control as an argument to ValidatorEnable javascript function. There is a reason why ValidatorEnable function is used instead of ValidatorValidate. ValidatorEnable function, after calling ValidatorValidate, calls another function ValidatorUpdateIsValid to set the value of Page_IsValid (ASP.NET generated javascript global variable) variable whereas ValidatorValidate executes the validation logic attached to the validation control and sets the isvalid property of the validation control.

So we have seen various ways to work with ASP.NET validation controls in javascript. We have seen how to call an individual validation control, how to call the whole page level validation and also how to access all the validation controls in a page.

In my next blog we will see how to hide and show ValidatorCallout controls using javascript. Before winding up this blog I would like to highlight another function which many of us require while working with string object in javascript. Its the trim function. You can see the details of it in this blog.


Try to know more


Sandeep

33 comments:

  1. Thank you so much for this post. It really helps and saved me huge amount of time.

    ReplyDelete
  2. Oh gr8 2 hear tht. Always happy to help u guys.

    ReplyDelete
  3. helpful n good post. Thanks...

    ReplyDelete
  4. thanx....really a nice post...
    but sandeep ...
    can we show message on validation summary using ValidatorEnable or ValidatorValidate Method

    ReplyDelete
  5. Hi Abhijit,
    Yes its possible. Even the validator callout control will be displayed using the two functions.

    ReplyDelete
  6. Really good post, but I am not able to show the error message in validation summary using the ValidatorValidate Method.
    Am I missing something?

    ReplyDelete
  7. Hi Meghana,
    It will great if you could send across the code which are using.

    ReplyDelete
  8. This comment has been removed by the author.

    ReplyDelete
  9. Hi Hong,
    You need to first set the display property of each validation control in the page to "None" and also make sure all the validation control have "ErrorMessage" property. These are the two things which you should make sure and the rest, the system will take care. Hope this helps.

    Regards,

    Sandeep

    ReplyDelete
  10. Thanks for the share. It really helped me alot to know more alot about validators and accessing it through javascript. Keep it up!

    ReplyDelete
  11. Hello Sandeep,
    I have a usercontrol with a textbox and a custom validator control. In the client script of this custom validator control how do i set the isvalid to false or true?
    Thanks

    ReplyDelete
  12. Hi Vidhya,
    Sorry for the late reply, was held up with work. When we use "CustomValidator" we provide the client side validation function. If you want to set "IsValid" then you can do it inside the function. Sample JS code is pasted below.
    function testCheck(source, arguments) {
    if (arguments.Value == "")
    arguments.IsValid = false;
    else
    arguments.IsValid = true;
    }
    Hope this helps.

    ReplyDelete
  13. THANK YOU SOOO MUCH!!!

    ReplyDelete
  14. Hi Matt,
    Happy know that the blog helped you.

    ReplyDelete
  15. Hello,

    This post was really useful, i had been searching for this technique for more than 2 hours.Thank you. I am having the same problem that Meghana has reported. Do you have any ideas on how to get the Validation Summary control also to display the ErrorMessage?


    Thanks and good day

    ReplyDelete
  16. Hi Kavitha,
    Are you facing any prob in displaying the error? If so please post the same. If you make use of ValidatorValidate method it will display the error messages in validation summary control. Also it will great if you could send across the code where which is giving problem.

    ReplyDelete
  17. Please take a look at the code below.I have a textbox that needs to fire a required field validator onBlur and also a validation summary control that should display the error message. The summary is getting displayed only when i click the submit button on the page.

    Note that i have enclosed it within a radAjaxPanel control








    Address:



    function validateAddr(sender){
    if (sender.value == "") {
    ValidatorValidate(Page_Validators[0]);
    }
    }

    ReplyDelete
  18. Oh...looks like the code i am posting is getting cut off

    ReplyDelete
  19. Hi Kavitha,
    With the above information it will be very difficult for me to suggest a solution. If you could send me your aspx and aspx.cs to my mail id it will be great. Mail id: sndppr@gmail.com

    ReplyDelete
  20. Sandeep, great post, tnx !

    real life saver :)

    ReplyDelete
  21. good article
    thanks

    ReplyDelete
  22. Helpfull post! Thanks alot!

    ReplyDelete
  23. Cheers was exactly what I was after.

    ReplyDelete
  24. this helps me a lot but, could yu pls add a link to download the code easily?

    ReplyDelete
  25. Hi,
    Do you know why in ie8 Validator is DispHTMLSpanElement and in ie9 HTMLSpanElement?
    How can I change it in ie9 to disphtmlspanelement?

    ReplyDelete

Please provide your valuable comments.