0

I want to the override default client side validation for only one form field.

what I did is:

  $( ".txt-field" ).change( function( event )
  {
     if ( !checkField( $(this).val() ) )
     {
        $(this).removeClass("valid").addClass("input-validation-error");
     }
     else
     {
        $(this).addClass("valid").removeClass("input-validation-error");
     }
  } );

and my HTML is

           <div class="fields">
               @Html.LabelFor( m => m.BlahBlah.Field, "Field" )
               @Html.TextBoxFor( m => m.BlahBlah.Field, new { @class = "textbox txt-field" } )
           </div>

but it's not working. checkField function returns true/false. When I'm at the javascript debugger, and the checkField returns false, I see the input-validation-error class to be added to my input field but then right after that, it is removed and "valid" class is added to it! what am I doing wrong???? I have removed any model validation attributes like "required", "maxLength", etc..

2 Answers 2

1

Try to add logic on "blur" method instead of "change" method.

 $( ".txt-field" ).blur( function( event )
{
 if ( !checkField( $(this).val() ) )
 {
    $(this).removeClass("valid").addClass("input-validation-error");
 }
 else
 {
    $(this).removeClass("input-validation-error").addClass("valid");
 }

} );

Sign up to request clarification or add additional context in comments.

1 Comment

thank you!! but can you please explain me why blur worked instead of change??
0

I found mistakes in your logic. In else block first should remove class then add new class. verify following code :

  $( ".txt-field" ).change( function( event )
  {
     if ( !checkField( $(this).val() ) )
     {
        $(this).removeClass("valid").addClass("input-validation-error");
     }
     else
     {
        $(this).removeClass("input-validation-error").addClass("valid");
     }
  } );

1 Comment

thank you but still not working. valid class is added although checkField method returns false, even if I comment the else block.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.