@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.

5 comments

  1. This post and the previous post would be great additions to the wiki.

    http://wiki.cakephp.org
  2. Gladly!



    The full article can be found at: http://wiki.cakephp.org/tutorials:alternate_advanced_validation
  3. Pingback: Bloggy Hell » Blog Archive » Update: Improved validation in CakePHP for version 1.x
  4. Hi, I meet some errors using your method, could you help me? Feel free to drop me a mail, thanks!
  5. Check out http://myles.eftos.id.au/blog/archives/51 - there is an updated version there - the internals have cheanged in CakePHP 1.0 so the above breaks

Leave a comment