Yii Extensions

Home made extensions for the Yii Framework.


  •  back to homepage
    jformValidate logo

    Important : Since Yii 1.1.7, client-side validation has been added to the core CActiveForm Widget, so if you're using version 1.1.7 (or more) of Yii you don't need to use this extension to enable client-side validation.

    Presentation

    JFormValidate is a Yii extension dedicated to provide Javascript Form Validation feature, for the Yii framework. This extension relies on an existing JQuery plugin that provides all the logic and functionnalities for the actual client-side Form validation. It is a powerful plugin, with plenty of intresting features that are described in its official documentation.

    Requirements

    • Yii framework 1.1.0 or more.
    Please note that previous version of Yii are not supported by this version of the extension. For the 1.0x Branch of Yii, the latest available release of jformvalidate is v 1.0.0.9 that can be download from the Yii Extension Repository
    It is not maintained anymore.

    Installation

    The released archive contains following files and folders :

    • jformvalidate.zip
      • extensions : the JFormValidate Yii extension itself including its dependencies. Note that the JQuery Validate Plugin is provided in this release.
      • sampleApp : this folder contains a set of files that can be added to a skeleton Yii app in order to demonstrate some functionalities of the JFormValidate extension. Most of these examples are available on the demo site.
        • controllers : JsvformController controller
        • models : TestForm model, derived from CFormModel
        • views
          • jsvform : this folder contains a set of view built from the TestForm model and aim to illustrate some aspects of the JFormValidate extension

    Install the extension in an existing webApp

    1. copy the content of the jformvalidate.zip/extensions folder into yourwebApp/protected/extensions
    2. Declare and initialize the new component in your application's configuration file.
          'jformvalidate' => array (
          	'class' => 'application.extensions.jformvalidate.EJFValidate',
           	'enable' => true
          ),
    3. import the EHtml helper class. This step is optional, as you could use the extension be refering directly to it as a loaded component. Since version 1.1, EHtml is the only way to use this extension.
          'import'=>array(
             ...
             'application.extensions.jformvalidate.EHtml',
             ...
           ) 	
       

    Now, the extension will be loaded the first time it is needed, but of course it is also possible to add it to the preload sequence.
    The 'enable' initialization argument (default to true) can be used to easely enable/disable the jformvalidate extension.
    For more information on extensions, please refer to the Yii Documentation.

    Install samples

    • Starting from a fresh Yii skeleton application, copy the content of jformvalidate.zip/sampleApp into yourApp main folder.
    • in your favorite browser access to http://yourdomain/yourApp/index.php?r=Jsvform/TestForm
    You can now tests some features with the different forms provided as sample.

    Quickstart

    Ok, let's see it in action ! For this first example, and assuming that the extension is correctly installed, we'll add Javascript validation to the Contact form that is automatically created with Yii skeleton application.
    This only requires to modify the corresponding view file, as describes below :

    1. edit the view file protected/views/site/contact.php
    2. with your favorite search and replace tool, replace all occurences of
      CHtml
      with
      EHtml

    That's it ! The contact form is now validated on the client side, according to the rules defined by the corresponding Yii model. Of course there are some configuration and CSS to set up in order to get a nice design, but the form validation is up and ready.

    How does it work ?

    The EHtml class wraps all helper static methods from the CHtml Yii core class, and by doing so, collects information on the form that is being built. When the endForm() method is invoked, all this information is used to generate a javascript initialisation object for the JQuery Plugin validation. Therefore, this extension can be considered as some sort of adaptater/converter between validation rules defined by a Yii model, and validation rules implemented by the JQuery Validate plugin.

    Upgrade from 1.0.x

    This version supports Yii 1.1 Branch but very few changes (if not no changes at all) must be done on your forms to be able to work fine with it.

    • scenario : to follow Yii scenario handling changes, the call to EHtml::setScenario() is not needed anymore as the extension directly gets the scenario from the model itself.
    • dependencies : in order to reduce dependencies between jformvalidate and the CHtml helper class, almost all calls to CHtml methods have been removed from the EJFValidate application component. This has 2 cosequences:
      • EHtml class is now the only way to use this extension. In other words, if you used to call
        Yii::app()->jformvalidate->activeTextField($model,'username');
        
        that is you were using the application component and not the EHtml class, you must now call :
        EHtml::activeTextField($model,'username');
        
        and use the EHtml class !
      • If you want to replace CHtml with another class you will have to modify EHtml.php and make it inherit this new class, but please note that following methods are invoked from the EJFValidate application component : CHtml::activeName(), CHtml::activeId, CHtml::encode and CHtml::normalizeUrl()

    Limitations

    Please note that method and class based validators are not supported by this extension, as it is not possible to automatically produce a JS code from a specific piece of PHP code (if you know how to do it, be my guess).

    In this version, the following set of Yii built-in validators is supported :

    • required
    • length : min, max or both
    • email
    • url
    • compare : with another attribute (compareAttribute) or a constant value (compareValue)
    • numerical : with options integerOnly, min, max, tooBig, tooSmall
    • match : note that pattern modifiers are not supported, except for /i
    Consequently, if you use another rule in your model, it will not be tested on the client-side, it will have to be added manually.

    using a JS validator

    If you need to validate user inputs on the client side, with a rule that is not (yet) implemented by this extension you can do so, by using the pseudo validator provided with the extension.
    This validator is a standard Yii validator class (it inherits from CValidator) but it is describes as pseudo because its only goal is to wrap calls to Javascript validators which are part of the underlying JQuery plugin. Therefore, when the pseudo validator is called by the Yii framework to validate an attribute, it always return true.

    Let's take a look at an example. The JQuery Plugin has a validator rule called remote which is used to validate a user entry through an ajax call to the server. So, let's say we want the user to enter his/her email, and that this email must not be already in use (this rule is equivalent of the Yii unique rule). The initialisation value for the remote validator, is the url that is in charge of testing email unicity.
    In the model, we add the following rule :

    array('custom1', 'application.extensions.jquery-form-validator.ECustomJsValidator',
    	'rules'    => array(
    		'remote' => 'index.php?r=Jsvform/remoteValidate'
    	),
    	'messages' => array(
    		'remote' => '{attribute} already registred'
    	)
    ),
    ..and that's it. Ok, you have to add the actionRemoteValidate() method to the JsvformController, but that's an easy task.
    (check this demo form or form7.php provided in the sample webapp)

    As you can see in the example above, the ECustomJsValidator class accepts a rule and a messages parameters, as described by the JQuery Plugin documentation.

    Ajax submition

    Implementing ajax submition with client-side validation is simple, as it doesn't require anything else than what is required by Yii ! A call to EHtml::ajaxSubmitButton() is enough to inform the Extension that ajax submition is needed. When this function is invoked, the JFormValidate extension will handle javascript creation and event handler registration instead of Yii.
    For a complete example, take a look at sample form13 and form14.

    Error messages

    In case an input field is not valid on the client-side, an error message is displayed. This error message comes from :

    1. the message parameter from the rule, as it is defined in the model
    2. when a Yii built-in validator is used, and no message is set as rule parameter, the default error message is used
    3. when a client-side-only validator is used, then a message defined in the javascript source code is displayed
    You may also note that in the two first cases, the special placeholder {attribute} will be replaced by the name or the label of the attribute whose validation failed.

    API Description

    Initialisation

    In the configuration file, it is possible to set some initialization parameters.

    • pluginOptions : this option should contains an array off options that will be passed with no change, to the JQuery Plugin. For more information on these options, please refere to the "Options for the validate() method" page.
    • enable : (boolean) - this option can be used to quickly disable all client-side validation handled by this extension.

    Public Methods

    In this version of the extension, only a reduced set of the Yii CHtml helpers methods have been wraped.

    • form element
      • form and beginForm
      • endForm
    • form construction
      • activeCheckBox
      • activeCheckBoxList
      • activeDropDownList
      • activeListBox
      • activePasswordField
      • activeRadioButtonList
      • activeTextArea
      • activeTextField
      • ajaxSubmitButton

    The JFormValidate extension provides also specific methods to perform specific tasks.

    • setOptions(array) : the arrays passed as argument should contain options that will be passed to the JQuery Plugin (see pluginOptions above).These options will override the ones defined by the application configuration, providing you with more flexibility.
    • setScenario(string) : use this method in the view where your form is built so to set the name of the Yii scenario.The JFormValidate extension will use this name to select rules that apply to this scenario only.
    • endForm() : this is the method that produces the javascript initialisation code for the JQuery Validate plugin. If you don't invoke this method, no javascript validation will occur. This method returns the form closing element "</form>"
      Since Yii version 1.0.5, this method has been added to CHtml helper class

    Overloading the submit handler

    The JQuery Validate plugin allows to overload the submit default handler (see related documentation). If you choose to do so, you must include a call to $.fn.EJFValidate.restoreName() in your own submit hanlder. This javascript function is provided with the extension because a call to some CHtml helpers method, generates HTML input elements with duplicated names. The problem is that the JQuery Validate Plugin works with input elements names, and duplicates name are not welcomed. The Extension will temporary remove duplicate name, and they must be restores before form submition. That's what the restoreName javascript function does. Below is an example of how is it possible to overload the submit handler :

    <?php	
    echo EHtml::beginForm(); 
    
    EHtml::setOptions(array(
    	
    	// ... put other options here ...
    		
    	'submitHandler' => 'function(form){
    		$.fn.EJFValidate.restoreName();
    		alert("submting the form");
    	}'
    ));
    ?>
    
    Check the sample form7 and form8 for live examples.

    Note that starting from version 1.0.4, all customizable hanlders available in the JQuery Validate Plugin options, can be overloaded with the same principle. This can be done at the form level (like in the example above) and of course at the configuration level, in your application configuration file, when declaring the EJFValidate extension.

    License

    Copyright (c) 2009-2010 by Raoul All rights reserved.
    Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
    Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of Raoul nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE


    bootstrap - Copyright © 2024 by Raoul.
    All Rights Reserved.
    Powered by Yii Framework.