Dan Pouliot
Dan Pouliot

Reputation: 415

jQuery Validate: required field is empty but validating true

Here is what I am seeing in my web console:

validationRules.rules.NameOnCard.required //true

document.OForm.NameOnCard.value //""

$("#OForm").validate().element("#NameOnCard") //true

The field is required, it is empty, and it is valid. What am I doing wrong?

As a bit of background, I programmatically make payment info not required until the form shows a balance, then I make it required. If I remove that if/then code, it properly validates. But from what I can tell I am correctly telling validator that that field is now required, so an empty field should validate to false, yes?

Upvotes: 0

Views: 2922

Answers (2)

ryankeairns
ryankeairns

Reputation: 808

Have your required parameter be conditional like this:

NameOnCard: {
required: function(element){
      var fooValue = $('#fooVar').val();
      if (isNaN( fooValue )){
          return false; 
      } else {
        if ( fooValue > 0) {
           return true;
        } else {
           return false;
        }
      }
}
}

Upvotes: 0

Troy Barlow
Troy Barlow

Reputation: 313

You'll want to check if the form is valid by doing this:

if($("#OForm").valid()){
 // valid
}

Upvotes: 1

Related Questions