Sun 17 Feb 2008
Automagic JavaScript Validation Helper - Beta
Posted by Matt under CakePHP , Code Snippets , Frontend , Javascript , PHP , Sandbox , jqueryWay back when CakePHP had a wiki there were a series of articles on “Advanced Validation.” One aspect of these articles was using the Model rules in JavaScript to validate on the client side. The code (I believe this is it) was originally for CakePHP version .10 (iirc). I had been using a heavily modified version of this code even in my 1.2 projects, but it was due for a ground up re-write.
I wrote an article for PHPArch not too long ago with a generic PHP approach for JavaScript validation. Using that JavaScript as a base, I created a helper to convert the model rules into JavaScript.
Here are the links:
Download
Instructions
Demo
This is all very beta, so please let me know if you find an issue. The helper should work with the three formats for defining validation in your model (output from bake, one rule per field, multiple rules per field).
If you are worried about security, there is an option to only include certain rules. See the tips section at the end of the instructions. Thanks to Marc for suggesting this.
Popularity: 96% [?]











February 18th, 2008 at 9:17 pm
[...] Automagic JavaScript Validation Helper - Beta :: PseudoCoder.com This looks interesting. Uses jQuery and your model definitions to provide javascript validation for forms (tags: cakephp jquery validation) [...]
February 27th, 2008 at 4:33 am
I have been needing to check out JQuery with Cake - seems 90% use it now!
but, I should add I have used with some success a js library which complements the CakePHP method - you just add a class name and it is very similar / simple to get going.
http://tetlaw.id.au/view/javascript/really-easy-field-validation
February 27th, 2008 at 6:40 am
Hey Luke,
Thanks for the link. I’m sure you could write a helper that takes your model validation rules and converts them into a format suitable for this lib.
-Matt
April 2nd, 2008 at 11:00 am
I dig this approach — the big argument against such is when the validation logic to too complex or too sensitive to convert to or expose in javascript.
The best solution would be one that can convert some of the cake validation logic into javascript for the sake of speed and then seamlessly use xhr calls to check the other fields (and ultimately falling back to server-side checks if js is not available).
This is doable with http://docs.jquery.com/Plugins/Validation but there are a couple snags with the current implementation plugin:
- it doesn’t currently allow returning of error messages (should be trivial)
- (as far as I can tell) it will use a http request for each field which also means they’re submitted separately
Regardless,
Thanks for your work Matt!