I'm using the jQuery Validation Plugin and I am adding my own methods like so:
jQuery.validator.addMethod("num", function(num) {
if(isNaN(num))
return false;
return true;
}, "Please enter a valid number");
However, even if I don't add the required
class to a form element, this validation method will still be called and evaluate to false if the user entered nothing. But I would like the behavior to be that if an element does not have the required
class, it is only called if the user has entered something. Is there anyway to do this? Thanks!
UPDATE
So the actual code that I posted above was meant to be a simple example to demonstrate the problem, however now I am putting up the specific example that is giving me issues. Here is the jsfiddle link:
The HTML
<form method="post">
<li>
<label for="2">Mileage</label>
<input type="text" name="2" id="attr_2" class="non_neg_int"
value="" />
</li>
<li>
<label for="3">VIN (Vehicle Identification Number)</label>
<input type="text" name="3"
id="attr_3" class="vin" maxlength="17" value="" />
</li>
<li>
<input type="submit" />
</li>
</form>
The JS
$(document).ready(function () {
var validator = $("form").validate({
onkeyup: false,
onblur: true,
ignore: "",
submitHandler: function (form) { // for demo
alert('valid form submitted'); // for demo
return false; // for demo
}
});
});
jQuery.validator.addMethod("vin", function (vin) {
if (!(/^[A-HJ-NP-Z0-9]{17}$/.test(vin))) return false;
return true;
}, "Must be a valid VIN");
jQuery.validator.addMethod("non_neg_int", function (non_neg_int) {
if (isNaN(non_neg_int) || non_neg_int == null || non_neg_int == "" || non_neg_int < 0 || !is_int(non_neg_int)) return false;
return true;
}, "Must be a nonnegative integer");
function is_int(value) {
if ((parseFloat(value) == parseInt(value)) && !isNaN(value)) {
return true;
} else {
return false;
}
}