Background: I have a jQuery validation script, which is used on almost all my webpages, allowing for client-side validation (I also do server-side validation). The javascript is the same for all my pages, except for the specific ‘rules’ for each form.
The rules for each page are inserted into a php variable $jquery_validation from my controllers prior to rendering the HTML page. This means I can dynamically generate each html page & form, with the appropriate client-side validation rules.
Below is my javascript code that is currently loaded on ALL my html pages:
$(document).ready(function(){
$('#signupform').validate({
wrapper: 'span class="error"',
meta: 'validate',
highlight: function(element, errorClass, validClass) {
if (element.type === 'radio') {
this.findByName(element.name).addClass(errorClass).removeClass(validClass);
} else {
$(element).addClass(errorClass).removeClass(validClass);
}
var error = $(element).parent().find('span.error');
error.show();
},
unhighlight: function(element, errorClass, validClass) {
if (element.type === 'radio') {
this.findByName(element.name).removeClass(errorClass).addClass(validClass);
} else {
$(element).removeClass(errorClass).addClass(validClass);
}
$(element).parent().find('span.error').hide(0, function() {
$(element).parent().find('span.valid').fadeIn(200);
});
},
<?=$jquery_validation?>);});
</script>
the $jquery_validation variable at the end contains the “rules” for each page, which are obviously different depending on the form. An example of the output it gives is:
"rules":{"username":{"required":true,"remote":{"url":"http:\/\/localhost\/mytest\/public_html\/welcome\/remote","type":"post"}},"onkeyup":false});});
The function is working now, and all is good.
Question: Is there a way to have my validation javascript function in my .js file (so it can be compressed etc) – and still dynamically load the “rules” section of the validation for each page?
I can change the ‘output’ & syntax of the $jquery_validation if required – but the point is I need to be able to output the rules for each page dynamically
Yes, you can create an object and save it off to a variable and save off the details in the constructor (can’t remember what it’s called in JS).
Here is an example I use in one of my scripts.
With that defined you can then instantiate it wherever you want and pass in whatever details you need.
The search Agent function, prototyped into the object: