Configuring our application to use unobtrusive validation

This new feature will allow us to configure our validator controls for the use of unobtrusive client validation logic in a very simple way. A very significant benefit of doing this is the reduction of the amount of JavaScript rendered in the page, making it substantially smaller.

Note that unobtrusive means not obtrusive or undesirably noticeable, which is generally a good practice for JavaScript, meaning that there is a separation of responsibility between the web page (presentation) and its behavior.

Getting ready

In order to use this recipe you should have Visual Studio 2012. We will use this as well as the application generated from our previous recipe.

How to do it...

Here we will create a sample app and see how to apply unobtrusive validation to it and how it affects the resulting HTML.

  1. Open our previous ASP.NET application or create a new one.
  2. Open the Web.Config file.
  3. Locate the <appSettings> element.
  4. If it doesn't exist, add the following setting inside the element found previously:
    <add key="ValidationSettings:UnobtrusiveValidationMode" value="none" />
  5. We will open our Book.aspx page and add the following code (a control and two validators) at the end of the ItemTemplate section:
    <asp:TextBoxID="TbValidation"runat="server"/>
    <asp:RequiredFieldValidatorID="tbvalidator1"runat="server"ErrorMessage="The field is required.."
    ControlToValidate="TbValidation"EnableClientScript="true"/>
    <asp:RangeValidatorID="tbrangevalidator1"runat="server"ErrorMessage="The range allowed is from 10 to 100"
    ControlToValidate="TbValidation"EnableClientScript="true"/>
  6. Next we execute the application and will see that the generated HTML looks as follows:
    <input name="ctl00$FeaturedContent$BookDetails$TbValidation" type="text" id="FeaturedContent_BookDetails_TbValidation" />
    <span id="FeaturedContent_BookDetails_tbvalidator1" style="visibility:hidden;">The field is required..</span>
    <span id="FeaturedContent_BookDetails_tbrangevalidator1" style="visibility:hidden;">The range allowed is from 10 to 100</span>
  7. We can see that the handling of this validations has generated a lot of JavaScript code after the HTML code:
    <script type="text/javascript">
    //<![CDATA[
    var Page_Validators =  new Array(document.getElementById("FeaturedContent_BookDetails_tbvalidator1"), document.getElementById("FeaturedContent_BookDetails_tbrangevalidator1"));
    //]]>
    </script>
    
    <script type="text/javascript">
    //<![CDATA[
    var FeaturedContent_BookDetails_tbvalidator1 = document.all ? document.all["FeaturedContent_BookDetails_tbvalidator1"] : document.getElementById("FeaturedContent_BookDetails_tbvalidator1");
    FeaturedContent_BookDetails_tbvalidator1.controltovalidate = "FeaturedContent_BookDetails_TbValidation";
    FeaturedContent_BookDetails_tbvalidator1.errormessage = "The field is required..";
    FeaturedContent_BookDetails_tbvalidator1.evaluationfunction = "RequiredFieldValidatorEvaluateIsValid";
    FeaturedContent_BookDetails_tbvalidator1.initialvalue = "";
    var FeaturedContent_BookDetails_tbrangevalidator1 = document.all ? document.all["FeaturedContent_BookDetails_tbrangevalidator1"] : document.getElementById("FeaturedContent_BookDetails_tbrangevalidator1");
    FeaturedContent_BookDetails_tbrangevalidator1.controltovalidate = "FeaturedContent_BookDetails_TbValidation";
    FeaturedContent_BookDetails_tbrangevalidator1.errormessage = "The range allowed is from 10 to 100";
    FeaturedContent_BookDetails_tbrangevalidator1.evaluationfunction = "RangeValidatorEvaluateIsValid";
    FeaturedContent_BookDetails_tbrangevalidator1.maximumvalue = "";
    FeaturedContent_BookDetails_tbrangevalidator1.minimumvalue = "";
    //]]>
    </script>
    
    
    <script type="text/javascript">
    //<![CDATA[
    
    var Page_ValidationActive = false;
    if (typeof(ValidatorOnLoad) == "function") {
        ValidatorOnLoad();
    }
    
    function ValidatorOnSubmit() {
        if (Page_ValidationActive) {
            return ValidatorCommonOnSubmit();
        }
        else {
            return true;
        }
    }
    
    document.getElementById('FeaturedContent_BookDetails_tbvalidator1').dispose = function() {
        Array.remove(Page_Validators, document.getElementById('FeaturedContent_BookDetails_tbvalidator1'));
    }
    
    document.getElementById('FeaturedContent_BookDetails_tbrangevalidator1').dispose = function() {
        Array.remove(Page_Validators, document.getElementById('FeaturedContent_BookDetails_tbrangevalidator1'));
    }
    //]]>
    </script>
  8. We will go back to the settings in the Web.config file and change the value to WebForms:
    <add key="ValidationSettings:UnobtrusiveValidationMode" value="WebForms"   />
  9. Executing the application again will generate the following code:
    <input name="ctl00$FeaturedContent$BookDetails$TbValidation" type="text" id="FeaturedContent_BookDetails_TbValidation" />
    <span data-val-controltovalidate="FeaturedContent_BookDetails_TbValidation" data-val-errormessage="The field is required.." id="FeaturedContent_BookDetails_tbvalidator1" data-val="true" data-val-evaluationfunction="RequiredFieldValidatorEvaluateIsValid" data-val-initialvalue="" style="visibility:hidden;">The field is required..</span>
    <span data-val-controltovalidate="FeaturedContent_BookDetails_TbValidation" data-val-errormessage="The range allowed is from 10 to 100" id="FeaturedContent_BookDetails_tbrangevalidator1" data-val="true" data-val-evaluationfunction="RangeValidatorEvaluateIsValid" data-val-maximumvalue="" data-val-minimumvalue="" style="visibility:hidden;">The range allowed is from 10 to 100</span>
  10. We can observe that this is different from before, with a few data attributes rendered that have the information the validator needs. On the other hand, we will find that no inline JavaScript code has been generated this time.

How it works...

We just had to add a setting into Web.Config file; however, unobtrusive validation is enabled by default in new projects, so in most cases, even if this setting is not there, it is active.

There's more...

We could also configure it from code, setting System.UI.ValidationSettings.UnobtrusiveValidationMode to UnobtrusiveValidationMode.WebForms or setting this on a particular page and changing the page's UnobtrusiveValidationMode property to UnobtrusiveValidationMode.WebForms or none.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset