Abhishek Ghosh
Abhishek Ghosh

Reputation: 2706

How can I change CSS Class of a textbox on failed Validation and then again change it back on successful validation?

I have a registration page with the bootstrap styling. I have <asp:RequiredFieldValidator> and <asp:RegularExpressionValidator> to validate the form.

Now i want to change the style if the validation fails and it should change back to normal when the validation is successful .

I have found a couple of answers like : txtBox.CssClass += "error_class" ;.

But i want to know how can it be done the exact way. I found a script which did change CSS based on failed validation ,but upon successful validation it did not change to original CSS .

original css class of textbox : form-control

What will be the easiest way to do this , like setting border-color to red...??

P.S. : In the bootstrap template i am using , there are two fields : id and class . Here :

class : form-control

id : inputError

Current method to change class :

<script type="text/javascript">
        function BtnClick() {
            var val = Page_ClientValidate();

            if (!val) {
                var i = 0;
                for (; i < Page_Validators.length; i++) {
                    if (!Page_Validators[i].isvalid) {
                        $("#" + Page_Validators[i].controltovalidate).css("border-color", "red");
                    }
                }
            }
            return val;
        }
    </script>

Upvotes: 0

Views: 1398

Answers (1)

KHeaney
KHeaney

Reputation: 785

You should just need to add additional conditionals to check for the inverse condition. Also I would create a second class specifically for the invalid version.

<script type="text/javascript">
    function BtnClick() {
        var val = Page_ClientValidate();

        if (!val) {
            for (i = 0; i < Page_Validators.length; i++) {
                if (!Page_Validators[i].isvalid) {
                    if (!($("#" + Page_Validators[i].controltovalidate).hasClass("form-invalid")))
                        $("#" + Page_Validators[i].controltovalidate).toggleClass("form-control form-invalid");
                }
                else {
                    if (!($("#" + Page_Validators[i].controltovalidate).hasClass("form-control")))
                        $("#" + Page_Validators[i].controltovalidate).toggleClass("form-control form-invalid");
                }
            }
        }
        return val;
    }
</script>

Where form-control is your normal class and form-invalid is you class that adds the red border.

See here removeClass() if it exists and here jquery change class name if you want to change the method at all.

Upvotes: 1

Related Questions