CODEDIGEST
Home » Articles
Search
 

Technologies
 

Sponsored links
 

CodeDigest Navigation
 

Technology News
No News Feeds available at this time.
 

Community News
No News Feeds available at this time.
 
Highlight Input Controls when Validation fails in Asp.Net Validator controls

By Satheesh Babu
Posted On Oct 08, 2011
Article Rating:
Average Rating: 5
No of Ratings: 1
No of Comments: 4
Category: ASP.Net
Print this article.

Highlight Input Controls when Validation fails in Asp.Net Validator controls

 

Asp.Net control set has a set of validation controls that offers input validations without writing a line of code. Often the functionalities provided by the validation controls are suffice to satisfy the validation requirements in our projects. At times, we may need to have a different behavior when compared to the Asp.Net validator controls for handling the input validations.

One of my previous article Restrict Asp.Net Validator controls to Fire on Page Submit demonstrated customizing the Asp.Net validator controls to fire the validations only on click of submit button using JavaScript. Similarly, let’s see how we can highlight the input control (or the control in ControlToValidate) whenever the validation fails just to make the user to have a quick attention on the control to change its input in order to pass the validations.

This approach will provide a better user experience when our input forms have large number of input controls. Once this is in place, the users can identify the input control very easily that have the wrong data in a big input forms since it is highlighted. Something like below,

Change Background colour of TextBox when Validation fails in ASP.Net

To do this, I will use jQuery library for the client side scripting in this article. I assume you have created a new asp.net project in your visual studio to understand this article.

By default, when we use Asp.Net Validator controls the framework will emit a JavaScript array called Page_Validators in the output HTML populated with the list of Validator controls on the page. See Listing 1 below. This array will be in turn consumed by the inbuilt validation script emitted by Asp.Net (through WebResource.axd handler, you can see it in view source) along the page HTML for performing the validations on the client side.

 

Listing 1 – Validator Array

<script type="text/javascript">

//<![CDATA[

var Page_ValidationSummaries =  new Array(document.getElementById("ValidationSummary1"));

var Page_Validators =  new Array(document.getElementById("RequiredFieldValidator1"), document.getElementById("RequiredFieldValidator2"), document.getElementById("RegularExpressionValidator1"), document.getElementById("CompareValidator1"), document.getElementById("RangeValidator1"));

//]]>

</script>

 

Along with the above array, the Asp.Net also emits some data associated with every validation controls in the form of JavaScript object and let the inbuilt validation script consume it for performing the validations. See below,

 

Listing 2 – Validator Data

<script type="text/javascript">

//<![CDATA[

var RequiredFieldValidator1 = document.all ? document.all["RequiredFieldValidator1"] : document.getElementById("RequiredFieldValidator1");

RequiredFieldValidator1.controltovalidate = "txtName";

RequiredFieldValidator1.errormessage = "Name is mandatory";

RequiredFieldValidator1.display = "None";

RequiredFieldValidator1.evaluationfunction = "RequiredFieldValidatorEvaluateIsValid";

RequiredFieldValidator1.initialvalue = "";

var RequiredFieldValidator2 = document.all ? document.all["RequiredFieldValidator2"] : document.getElementById("RequiredFieldValidator2");

RequiredFieldValidator2.controltovalidate = "ddlGender";

RequiredFieldValidator2.errormessage = "Gender is mandatory";

RequiredFieldValidator2.display = "None";

RequiredFieldValidator2.evaluationfunction = "RequiredFieldValidatorEvaluateIsValid";

RequiredFieldValidator2.initialvalue = "0";

……trimmed for brevity

//]]>

</script>

 

We will make use of this information and with the help of jQuery let’s see how we can highlight the input control whenever the validation fails.

If we take a closer look at the data emitted by the Asp.Net framework in Listing 2, each validator control has a property called controltovalidate that holds the associated input control and initialvalue that holds the initial value the input control. The validator control will validate the input based on the initialvalue set in the property, in other words, the validation will fail if the initialvalue and value in input control matches for required field validations. The rest of the properties seen in the above listings are self explanatory. Apart from the above property each validator control has a property called isvalid which will return true or false based on the validation outcome. This property “isvalid” is the key of this article since it holds the validation outcome for individual validations.

 




The implementation

Firstly, we need to hook an onblur event handler for every input controls that is associated with each validator control in Page_Validators array. On this event, we can change the background (or highlight) based on the value of isvalid property. Assuming we have integrated the jQuery library in our project, I will dive into the code directly. Refer the below code,

<script src="_scripts/jquery-1.6.4.min.js" type="text/javascript"></script>

<script type="text/javascript">

    $(document).ready(function() {

        HighlightControlToValidate();

        $('#<%=btnSave.ClientID %>').click(function() {

            if (typeof (Page_Validators) != "undefined") {

                for (var i = 0; i < Page_Validators.length; i++) {

                    if (!Page_Validators[i].isvalid) {

                        $('#' + Page_Validators[i].controltovalidate).css("background", "#f3d74f");

                    }

                    else {

                        $('#' + Page_Validators[i].controltovalidate).css("background", "white");

                    }

                }

            }

        });

    });

 

    function HighlightControlToValidate() {

        if (typeof (Page_Validators) != "undefined") {

            for (var i = 0; i < Page_Validators.length; i++) {              

                $('#' + Page_Validators[i].controltovalidate).blur(function() {

                var validatorctrl = getValidatorUsingControl($(this).attr("ID"));                               

                    if (validatorctrl!= null && !validatorctrl.isvalid) {

                        $(this).css("background", "#f3d74f");

                    }

                    else {

                        $(this).css("background", "white");

                    }

                });

            }

        }

    }   

    function getValidatorUsingControl(controltovalidate) {      

        var length = Page_Validators.length;

        for (var j = 0; j < length; j++) {

            if (Page_Validators[j].controltovalidate == controltovalidate) {

                return Page_Validators[j];

            }

        }

        return null;

    }   

</script>

 

In the above code, I am setting the background color of the input control on onblur event and on onclick event of the submit button. This is because, the validation function associated with a validator control will be fired on both onblur and submit event. The key difference in setting the background color in both the event is how I am finding the associated validator control for an input control.

In onblur event, I am finding the associated validator control for a input control by passing its ID to getValidatorUsingControl() method. This method will search for the validator in the Page_Validators array and will return it, while this is not required in case of onclick or submit since every validator control needs to be fired when the submit button is clicked.

 

Downloads

Download Source

 

Conclusion

Since validations are integral part of any application we develop, it is also important that we provide a good user experience whenever we can offer to our users. This article discussed this in one way where we can provide a good user experience when we use the inbuilt validation controls available in Asp.Net.

Download the source attached with this article and see it in action.

Happy Coding!!

Similar Articles
You can contribute to CodeDiget.Com:
Donate to CodeDigest.com
Article Feedback
Comments
Validator Highlighter
Great Article! and its working fine.
Thanks
That's great !
It saved me several hours[maybe 1000 hours :)) ]

Great Article
Thanks a lot!!!!
The article really helped me to solve my problem :)
Brijesh
Really Nice Article Fried.
But Can we have autofocus on first validation ? I mean if we have 3 validation error can we focus our control directly on first validation control ? i.e. textbox or dropdown whaever...

If you have answer and tips let me know on shriji1111.brijesh@gmail.com

anyways thanks for your article.