9

I have a TextBox input element that has a RequiredFieldValidator as such:

<div>
    <label>First name</label>
    <asp:RequiredFieldValidator ID="RequiredFieldValidatorFirstname" runat="server" ErrorMessage="Required" ControlToValidate="TextBoxFirstname"></asp:RequiredFieldValidator>
    <asp:TextBox ID="TextBoxFirstname" runat="server"></asp:TextBox>
</div>

When the TextBox is empty on submit I want to add the class 'form-error' to the parent Div:

<div class="form-error">
    <label>First name</label>
    <asp:RequiredFieldValidator ID="RequiredFieldValidatorFirstname" runat="server" ErrorMessage="Required" ControlToValidate="TextBoxFirstname"></asp:RequiredFieldValidator>
    <asp:TextBox ID="TextBoxFirstname" runat="server"></asp:TextBox>
</div>

Is this possible, and if so - how do I do it?

hbruce
  • 934
  • 4
  • 11
  • 21
  • Check this [answer][1]. Hope this helps, [1]: http://stackoverflow.com/questions/1301508/change-textboxs-css-class-when-asp-net-validation-fails/12805078#12805078 – gsimoes Oct 09 '12 at 17:57
  • People coming for ASP.NET MVC / jQuery Validation might want to check [this answer](http://stackoverflow.com/q/10431944/1366033) – KyleMit Sep 28 '16 at 02:28

3 Answers3

10

Use the following:

<script>

    $(function(){
        if (typeof ValidatorUpdateDisplay != 'undefined') {
            var originalValidatorUpdateDisplay = ValidatorUpdateDisplay;

            ValidatorUpdateDisplay = function (val) {
                if (!val.isvalid) {
                    $("#" + val.controltovalidate).closest("div").addClass("form-error");
                }

                originalValidatorUpdateDisplay(val);
            }
        }
    });

</script>

This code decorates the original ValidatorUpdateDisplay function responsible for updating the display of your validators, updating the controltovalidate closest div.

gsimoes
  • 1,011
  • 11
  • 12
7

with RequiredFieldValidator you can not add your custom code.

you should use asp.net customvalidator control, and write your own custom validation javascript function which sets the class to the div.

Canavar
  • 47,715
  • 17
  • 91
  • 122
  • Thanks! That's great help. However - it seems that when my TextBox is empty the custom script is not invoked. Any thoughts on this? – hbruce Mar 05 '09 at 13:18
  • 3
    Found it out - turns out there's an option for the CustomValidator named ValidateEmptyText that needs to be set. :) Thanks for your help! – hbruce Mar 05 '09 at 13:26
3

I think you may find the below option useful. Basically it overrides one of ASP.NET validations default scripts. And shoves some logic into it to add / remove error class on parent div.

The problem I had faced with this task was getting my script to execute after validations were triggered since the DOM is not reloaded. By overriding this the original validation script you have the ability to run your own script when the validation display is updated.

This way you can continue to use your other validation controls. You do have to place the script at the bottom of your page or masterpage. I also used JQuery to make things simpler.

*Note the below code requires your validators be set to display dynamic. If you don't want them to be visible you can add a css class to them and set display: none.

<script type="text/javascript">
    function ValidatorUpdateDisplay(val) {
        if (typeof (val.display) == "string") {
            if (val.display == "None") {
                return;
            }
            if (val.display == "Dynamic") {
                val.style.display = val.isvalid ? "none" : "inline";
                return;
            }
        }
        if ((navigator.userAgent.indexOf("Mac") > -1) && (navigator.userAgent.indexOf("MSIE") > -1)) {
            val.style.display = "inline";
        }
        val.style.visibility = val.isvalid ? "hidden" : "visible";


        //---  Add / Remove Error Class
        var triggeredSiblings = 0;
        if (val.isvalid) {
            $(val).siblings('span').each(function () {
                if ($(this).isvalid == false) { triggeredSiblings = 1; }
            });
            if (triggeredSiblings == 0) { $(val).closest("div").removeClass("error"); }
        } else {
            $(val).closest("div").addClass("error");
        }
    }
</script>
Jeremy A. West
  • 2,162
  • 4
  • 27
  • 40
  • I know this post is old, but if you have many validators on the same input, you have to use `if (this.isvalid == false) { triggeredSiblings = 1; }` instead of `if ($(this).isvalid == false) { triggeredSiblings = 1; }` else if the second validator is valid but not the first one, error class is removed. – Pouki Apr 12 '16 at 12:14
  • I implemented this solution a couple years ago in a production environment, for the most part it was successful. That said I don't think I would do it again. For one thing it never worked correctly with dynamic content (hide and show). We just lived with that issue. Thanks for the fix, not sure if I had to correct that or not. – Jeremy A. West Apr 12 '16 at 18:52
  • Yes I noticed that also about the hide and show. It's for a POC I'm doing now, so I was researching some clues. Thank for the feedback ! – Pouki Apr 13 '16 at 09:10