@madpilot makes

Adding automatic JavaScipt validators to CakePHP

I’m reposting the validators.php file that I uploaded in my previous post, but this time adding a function that will automatically generate a javascript function called validate() that returns an array of error strings. This is made possible because CakePHP’s validation model uses regular expressions.

NOTE: This function has been written using my modified validator class. Please read my previous post to see what it is all about.

The strings and expressions are identical to the ones you get by callling $this->modelName->validates() in a controller, so you can avoid a round trip to the server in many cases.

To use, drop the validators.php into your app helpers directory (as before), and call the function $validators->javascriptErrors(‘modelName’); where modelName is the name of the model you want to pull the validation data from. For those of you playing at home, you may notice that the $modelNames variable gets converted to an array – this is because you can actually supply an array of modelNames if you need to validate the inputs from multiple models. Why? I had a need for it in a project, which I might go through later :)

Now, this isn’t quite complete, because it only returns an array of strings, you still need to output the string somehow. I usually output the strings to div, as I hate JavaScript alerts. The code for which is here. In that file I have defined a function called validateForm(form); which updates the div and returns false on an error, so you can use it in the onSubmit handler for the form.