Say i have a form that looks up city, state locations. if the user enters an incorrect city, state, i want the form to be able to check the database against the users input, and see if the input is valid or not. If it is not, i want the user to be prompt.
So form Validate is the plugin for me.
$("#form").validate({ rules: { citystate: { required: true, myCustomAjaxSyncronousCheckAgainstDBRule: true } submitHandler: function(form) { if ($("#form").valid()) { form.submit(); } } });
Now say this form has to be used in 4 different places in my website, so it would suck to refactor out the myCustomAjaxSyncronousCheckAgainsDBRule (Fake name btw) and have the same code 4 times throughout my website. So that is why i created a custom rule in the JS file. But is there a way that the rule CAN ONLY be checked at Submit time. Since if there is an invalid user input, it will check it at EVERY key stroke, which can be quite cumbersome. Especially since i have jQuery.ui.autocomplete running inconjuction.
All of the validations can be set independently (onclick, onkeypress,onsubmit,etc.)
Demos and details are available on the docs site http://docs.jquery.com/Plugins/Validation/validate
$("#form").validate({ onkeyup: false, onclick: false })
As an alternative an a more straightforward way you can pass a function to the onfocusout
and onkeyup
settings of the jquery.validator to decide if an element has to be validated in those events or not, as this :
jQuery.validator.defaults.onfocusout = function (element, event) { // detectect if is the element you dont want validate // the element has to have the attribute 'data-control="mycitycontrol"' // you can also identify your element as you please if ($(element).data("control") === "mycitycontrol") return; if (!this.checkable(element) && (element.name in this.submitted || !this.optional(element))) { this.element(element); } } jQuery.validator.defaults.onkeyup = function (element, event) { // detectect if is the element you dont want validate // the element has to have the attribute 'data-control="mycitycontrol"' // you can also identify your element as you please if ($(element).data("control") === "mycitycontrol") return; if (event.which === 9 && this.elementValue(element) === "") { return; } else if (element.name in this.submitted || element === this.lastElement) { this.element(element); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With