0

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!

Community
  • 1
  • 1
Adam
  • 6,041
  • 36
  • 120
  • 208

1 Answers1

1

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>
Arun Bertil
  • 4,598
  • 4
  • 33
  • 59
  • I read something about that too, but how would I then implement this for regularexpressionvalidator and in cases where I need to match two fields? (e.g. password match or email match) It seems that with your suggestion for those cases I would have to write all validation logic myself? – Adam Jul 24 '13 at 12:01