/js_validate

CakePHP Plugin - Convert model validation rules to JavaScript and apply on the frontend using jQuery

Primary LanguagePHP

/*
 * CakePHP jQuery Validation Plugin
 * Copyright (c) 2011 Matt Curry
 * www.PseudoCoder.com
 * http://github.com/mcurry/js_validate/
 * http://sandbox2.pseudocoder.com/demo/validation
 *
 * @author      mattc <matt@pseudocoder.com>
 * @license     MIT
 *
 */
 
/* Notes */
    * This helper requires jQuery. Sorry to all you Prototype/script.aculo.us users.
    * Tested on CakePHP 1.2.5 Stable and jQuery 1.3.2

/* ReadMe */
   1. Download the plugin and put it in /app/plugin/js_validate
   
   2. Optionally, put jquery.validation.min.js somewhere in your /app/webroot/js.
   
   3. Include the helper in any controller that will need it.
      var $helpers = array('JsValidate.Validation');
      
   4. Include the Javascript files in your view. 
      If you are already using jQuery throughout your app, and it is included in your layout, you can removed it from the line below.
      If you copied jquery.validation.min.js to your /app/webroot/js:
      $this->Html->script(array('jquery', 'jquery.validation.min'), false); 
      Alternatively, you can use the JavaScript right from the in the plugin directory:
      $this->Html->script(array('jquery', '/js_validate/js/jquery.validation'), false); 
      The downside to using this method is the javascript is loaded through PHP, which isn't as fast.

   5. Then in the views for your forms, call the helper. Replace "Model" with the model name for the form.
      echo $validation->bind('Model');

/* Extra */
   1. You can pass a second param to the method call above, which is an array of options. The available options are:
          * form - Any valid jQuery selector.  Defaults to "form".
                   If you wanted to target a form you'd most likely pass "#formId"
          * inline - Setting this to true will return the ouput for direct echoing. 
                     If false then the codeblock will be added to the output of $scripts_for_layout for display in the HEAD tag.
          * messageId - The id of a div where all the validation messages will be displayed. 
   2. If a particular field fails the input will be marked with the css class "form-error" 
      and the message will be added after the field with the class "error-message". 
      This is the same as Cake would do if you submitted to the server. 
      In addition you can specify a div messageId and all the messages will be shown there as well.
        <div id="message"></div>
        
/* Custom Rules and Error Handling */
   1. At the moment there are three callbacks: beforeFilter, setError and afterFilter.
      beforeFilter - called before validation is started. No params.
      afterFilter - called after validation is done. Passed an array of errors.
      setError - called anytime a validation error is found. Passed the field and the error message.
      
      If you wanted some alternate handling for errors you could do something like this:
      $.fn.validate.setError = function(field, message) {
        //don't ever do this or I will come for you
        alert(message);
      }

   2. It's up to you to write the custom function and you're free to use Ajax here.
      For example if you had a custom validation rule “myRule” you would define the function like this:
      $.fn.validate.myRule= function(val, params) {
        //do some validation here and return either true or false.
      }

/* Manual Form Handling */
You can disable the auto binding to the form by adding setting the catch option to false:
	echo $validation->bind('Model', array('catch' => false));

Then catch the submit and run the validation manually:
	$("#ModelForm").submit(function(event) {
	  //your own code here
	
	  //run the validation
	  valid = $.fn.validate.check($(this).data("validation"));
	  
	  //more code
	
	  return valid;
	});

/* Tests */
   1. CakePHP unit tests are available through the normal /test.php
   2. JavaScript unit test can be run by visiting /js_validate/test.
   
/* Tips */
   * I wrote an article for PHPArch about JavaScript validation(http://c7y.phparch.com/c/entry/1/art,improved_javascript_validation), which raised some concerns that this approach may reveal too much about an application's security. If this is a concern for you, but you still want to use this helper, there is an option to whitelist rules can be applied on the client side. To use to this feature set the list in your bootstrap.php:
     Configure::write('javascriptValidationWhitelist', array('alphaNumeric', 'minLength'));