Add class to textbox when invalid, using .Net Validators

Posted by CoreyT on Stack Overflow See other posts from Stack Overflow or by CoreyT
Published on 2010-06-15T19:28:14Z Indexed on 2010/06/15 19:32 UTC
Read the original article Hit count: 239

I'm working on a multipage form in .Net using AJAX (UpdatePanels). I am stuck right now trying to get a class added to the textbox that is invalid to basically highlight it red.

I found a sample online using this code:

                $("span.invalid").bind("DOMAttrModified propertychange", function (e) {
                // Exit early if IE because it throws this event lots more
                if (e.originalEvent.propertyName && e.originalEvent.propertyName != "isvalid") return;

                var controlToValidate = $("#" + this.controltovalidate);
                var validators = controlToValidate.attr("Validators");
                if (validators == null) return;

                var isValid = true;
                $(validators).each(function () {
                    if (this.isvalid !== true) {
                        isValid = false;
                    }
                });

                if (isValid) {
                    controlToValidate.removeClass("invalid");
                } else {
                    controlToValidate.addClass("invalid");
                }
            });

That works perfectly, in IE only. For some reason this code does not ever fire in Firefox. I've looked up the DOMAttrModified event and it sounds like this should work in Firefox, hence it being in the code. I must be missing something though because it does not work.

I'm open to other solutions for what I am trying to accomplish here if anyone has something good. Basically the form is 3 pages right now. Page 1 has a variable number of fields that require validation. It could be 5, or 13 fields, based on a checkbox. Page 2 has another set of fields that need to be validated separately. Obviously when I am on page 1 it should not try to validate page 2, and vice versa.

Pleas help with either some help to fix the code I have, or an alternative.

© Stack Overflow or respective owner

Related posts about ASP.NET

Related posts about JavaScript