No Name
No Name

Reputation: 612

jQuery Validation rule based on select value

I have the following form.

<form id="myform">
    <select id="country" name="country">
        <option value="US">United States</option>
        <option value="CA">Canada</option>
        <option value="AU">Australia</option>
        <option value="NZ">New Zealand</option>
        <option value="IE">Ireland</option>
    </select>
    <input type="text" name="zip_code" id="zip-code">
    <input type="submit">
</form>

I want the zip_code field to contain the digits: true rule when the selected country is United States. This is what I have tried based on this code.

$("#myform").validate({
    rules:{
        zip_code: {
            required: true,
            maxlength: 10,
            digits: function(element){
                return $("#country").val() == 'US';
            }
        }
    }
});

EDIT: I was mistaken, this does enable digits validation, but when I change countries, the digits rule doesn't become false

Upvotes: 0

Views: 813

Answers (1)

jvk
jvk

Reputation: 2201

here i notice few thing which you have done wrong, you have given variable instead of id,

   $("#myform").validate({
          rules:{
              zip_code: {
                  required: true,
                  maxlength: function() {
                    if($("#country").val() == 'US'){
                      return 5;
                    }else {
                      return 10;
                    }
                  },
                  digits: {
                  depends: function(element) {
                      return $("#country").val() == 'US';
                    }
                  }
              }
          }
      });

Upvotes: 1

Related Questions