celticharp
celticharp

Reputation: 155

asp net mvc custom client side validation for one field

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..

Upvotes: 0

Views: 1235

Answers (2)

Khalid
Khalid

Reputation: 194

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");
 }

} );

Upvotes: 1

rishikesh tadaka
rishikesh tadaka

Reputation: 483

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");
     }
  } );

Upvotes: 0

Related Questions