Skip to content

Instantly share code, notes, and snippets.

@pandurang90
Created December 1, 2015 10:40
Show Gist options
  • Save pandurang90/24b2589510e6e93b82f0 to your computer and use it in GitHub Desktop.
Save pandurang90/24b2589510e6e93b82f0 to your computer and use it in GitHub Desktop.
jQuery validation cheatsheet
// Change the default message of jquery validation
jQuery.extend(jQuery.validator.messages, {
required: "This field is required.",
remote: "Please fix this field.",
email: "Please enter a valid email address.",
url: "Please enter a valid URL.",
date: "Please enter a valid date.",
dateISO: "Please enter a valid date (ISO).",
number: "Please enter a valid number.",
digits: "Please enter only digits.",
creditcard: "Please enter a valid credit card number.",
equalTo: "Please enter the same value again.",
accept: "Please enter a value with a valid extension.",
maxlength: jQuery.validator.format("Please enter no more than {0} characters."),
minlength: jQuery.validator.format("Please enter at least {0} characters."),
rangelength: jQuery.validator.format("Please enter a value between {0} and {1} characters long."),
range: jQuery.validator.format("Please enter a value between {0} and {1}."),
max: jQuery.validator.format("Please enter a value less than or equal to {0}."),
min: jQuery.validator.format("Please enter a value greater than or equal to {0}.")
});
jQuery.validator.addMethod("greaterThanZero", function(value, element) {
return this.optional(element) || (parseFloat(value) > 0);
}, "* Amount must be greater than zero");
//And then applying this like so:
$('validatorElement').validate({
rules : {
amount : { greaterThanZero : true }
}
});
/*
1. .hidden is ignored by default
2. options for validate method
http://docs.jquery.com/Plugins/Validation/validate
*/
<select id="select" class="required">
<option value="">Choose an option</option>
<option value="option1">Option1</option>
<option value="option2">Option2</option>
<option value="option3">Option3</option>
</select>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js"></script>
$("form.contact").validate({
//onfocusout: function(element) { $(element).valid(); },
rules: {
email: { required:true, email: true},
username: { required: true }
},
// [optional] custom messages
messages: {
email: { required: "custom required field message", email: "Custom email message" },
}
// [optional] custom error placement
errorPlacement: function(error, element) {
}
});
// blur
$(element).blur(function() {
$("form.contact").validate().element($this);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment