0

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

2
  • except us other countries allow number only wright Commented Jul 31, 2018 at 15:15
  • @whoami US should be digits only. The other countries can have both letters and numbers. Commented Jul 31, 2018 at 15:17

1 Answer 1

1

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';
                    }
                  }
              }
          }
      });
Sign up to request clarification or add additional context in comments.

2 Comments

The variable was just a typo. However your answer seems to be working. I will mark it as accepted. I know this wasn't part of the original question but do you know how I could make it so the maxlength is 5 when the country is US, and 10 when it's any other country?
@BojanSrbinoski, i updated the answer, check it out.

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.