Reputation: 2510
I'm using the validator plugin for a form. I would use the method exactlength but with 2 numbers. I would check that the field is either 11 or 10 characters.
jQuery.validator.addMethod("exactlength", function(value, element, param) {
return this.optional(element) || value.length == param;
}, jQuery.format("Please enter exactly {0} characters."));
$("#formtovalidate").validate({
rules: {
somefield: {
exactlength: 10,
exactlength: 11
}
});
You can do it? How can I change the method to do this? Thanks
Upvotes: 0
Views: 385
Reputation: 388446
You can't pass the same key twice like that, what you need to do is to pass it as an array
jQuery.validator.addMethod("exactlength", function(value, element, param) {
if (this.optional(element)) {
return true;
}
if ($.isArray(param)) {
return $.inArray(value.length, param) != -1;
} else {
return value.length == param;
}
}, function(param, input) {
return jQuery.validator.format("Please enter exactly " + ($.isArray(param) ? param.join() : param) + " characters.")
});
$("form").validate({
debug: true,
rules: {
f1: {
exactlength: [10, 11]
},
f2: {
required: true,
exactlength: 3
}
}
});
//
$('#save').click(function() {
$('form').valid()
return false;
})
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.12.0/jquery.validate.js"></script>
<form>
<div>
<input name="f1" />
</div>
<div>
<input name="f2" />
</div>
<input id="save" type="button" value="save" />
</form>
Upvotes: 4