Need help using jQuery validation rules.

Need help using jQuery validation rules. I have a input field that needs specific rules. See below. I'm not sure if you can use range with multiple ranges.

Any help would be great thanks.

http://docs.jquery.com/Plugins/Validation




rules: {
      zip: {required: true, digits: true, maxlength: 9, minlength: 5},
}


1) Zip should accept either 5 or 9 digits.
2) Should not accept 6 digits or 7 digits or 8 digits.
yando18Asked:
Who is Participating?
 
leakim971PluritechnicianCommented:
check this : http://docs.jquery.com/Plugins/Validation/Validator/addMethod#namemethodmessage

test page : http://jsfiddle.net/cMyzS/

jQuery.validator.addMethod("zip5or9", function(value, element) {
  return this.optional(element) || value.length == 5 || value.length == 9;
}, "Please specify a correct zip");


rules: {
      zip: { required: true, zip5or9: true },
}

Open in new window


0
 
Kiran SonawaneProject LeadCommented:
leakim971's code is perfect just to show the correct message to end user what they need to enter

<head>
<meta http-equiv="Content-Language" content="en-gb">
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>Kiran Test</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js" type="text/javascript"></script>
  <script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.js"></script>
<script>
$(document).ready(function(){
  
  $.validator.addMethod("zip5or9", function(value, element) { 
    return this.optional(element) || value.length == 5 || value.length == 9 ; 
}, "Please specify a correct zip");
  
  $("#testForm").validate({
    rules: {
      zip: {
        required:true,
        digits:true,
        maxlength: 9,
        minlength:5,
        zip5or9: true
      }
      
    },
    messages:{
      zip: {
        required: "Please enter zip code",
        digits: "Enter digit only",
        maxlength: "9 digit max",
        minlength: "5 digit minimum",
        zip5or9: "Zip should be either 5 Or 9 digit only"
        }
    }
  });
});
</script>

</head>

<body>
<form method="POST" id="testForm" >
  <input name="zip" type="text">
  <input type="submit">
</form>
</body>

</html>

Open in new window

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.