Question

I currently have a form with about 10 controls like this:

<asp:TextBox ID="fullname" Width="200" MaxLength="50" runat="server"/>
<asp:RequiredFieldValidator Display="Dynamic" ValidationGroup="contact" ControlToValidate="fullname" ID="RequiredFieldValidator1" runat="server" ErrorMessage="*"/>

I love the way ASP.NET fieldvalidators work, with one exception: it's hard for me to override the fact that when the validation fails not an asterisk should be displayed as it is now, but instead the input field that failed should be highlighted in red.

I want to do the highlighting of the input field via jQuery so that I have full control over css/animation. I don't want to use the ASP.NET animation as it is overly complex in my opinion.

I also checked this post: Change Text Box Color using Required Field Validator. No Extender Controls Please but it does not provide a clear answer.

So: is there a way to keep my current ASP.NET validator controls, but override the displaying (and hiding) of their ErrorMessage property and instead use jQuery to add (or remove) an animation/css to the validated input field?

Requirements:
- code must work for requiredfieldvalidator/regularexpressionvalidator etc.
- capture enter key
- remove error css if user corrects the input field and validation is succesful

Thanks!

Was it helpful?

Solution

You need to use Custom Validator

aspx:

  <asp:TextBox ID="txtFirstName" runat="server"></asp:TextBox>
                <asp:CustomValidator ID="cvFirstName" runat="server" SetFocusOnError="true" Display="Dynamic"
                    ValidateEmptyText="true" ControlToValidate="txtFirstName" ClientValidationFunction="validateValue"></asp:CustomValidator>  

JS:

   <script type="text/javascript">
        function validateValue(source, args) {
            if (args.Value == "") {
                args.IsValid = false;
                document.getElementById(source.id.replace('cv', 'txt')).className = 'Invalid';                
            }
            else {
                args.IsValid = true;
                document.getElementById(source.id.replace('cv', 'txt')).className = 'Valid';
            }
        }  
    </script>

CSS:

 <style type="text/css">
        .Invalid
        {
            border: 1px solid red;
        }
        .Valid
        {
            border: 1px solid White;
        }

    </style>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top