The rules custom validation rule _php instance in the PHP Yii Framework Development Small skill model (models)

Source: Internet
Author: User
Tags tagname yii

The rules section of Yii's models is the validation rules for some forms, useful for form validation, a form is added to the corresponding view (views), and the program is automatically validated in the rules that precede the form submission, and can only be committed if the constraint rules are valid. Can effectively guarantee the safety of forms and the effectiveness of information. Or to give you a specific explanation:

The following is a simple code for the Views section:

<?php $form = $this->beginwidget (' Cactiveform ', array ( 
  ' id ' => ' tag-form ', 
  ' enableajaxvalidation ' = >false, 
)?> 
  <div class= "Row" > 
    <?php echo $form->labelex ($model, ' tagname ');?> 
    <?php Echo $form->textfield ($model, ' tagname ', array (' Size ' =>20, ' maxlength ' =>32));?> 
  </ div> 
  <div class= "Row" > 
    <?php echo $form->labelex ($model, ' tagtype ');?> <?php 
    Echo $form->radiobuttonlist ($model, ' Tagtype ' array (1=> "ordinary Tag",2=> "system default Tag"), Array (' Separator ' => ', ' Labeloptions ' =>array (' class ' => ' Tagtypelabel '))?> 
  </div> 
  <?php echo $form-> Errorsummary ($model);?> 
  <div class= "row Buttons" > 
    <?php echo chtml::submitbutton ($model-> Isnewrecord? ' Add ': ' Modify ');?> 
  </div> 

Simple code for the Rules section of the Model (models):

Public function rules () 
{return 
  array ( 
    ' tagname,tagtype ', ' required '), 
    array (' Tagtype ', ' Numerical ', ' integeronly ' =>true), 
    array (' tagname ', ' length ', ' Max ' =>32), 
    array (' tagname ', ' match ', ' Pattern ' => '/^[\x{4e00}-\x{9fa5}a-za-z0-9]+$/u ', the 
        ' message ' => ' label is illegal, must be Chinese characters, letters or numbers! '), 
    array (' tagname ', ' checktagname ', ' on ' => ' create,update '),//check whether the tag array already exists 
    (' TagID, tagname , Tagtype ', ' safe ', ' on ' => ' search ') 
  ; 

The system defaults to these validation rules:

Boolean:cbooleanvalidator alias to ensure that the value of the property is Cbooleanvalidator::truevalue or Cbooleanvalidator::falsevalue . 
Captcha:ccaptchavalidator alias to ensure that the value of the attribute equals the CAPTCHA display of the authentication code . 
Compare:ccomparevalidator alias, ensuring that the value of the attribute equals another attribute or constant .  the alias of the
Email:cemailvalidator to ensure that the value of the attribute is an alias for a valid e-mail address . 
Default:cdefaultvaluevalidator, assigning a default value to the attribute.  
Exist:cexistvalidator alias to ensure that the property value exists in the specified data table field . 
File:cfilevalidator alias, ensuring that the attribute contains the name of an upload file . 
Filter:cfiltervalidator alias, using a filter conversion property . 
In:crangevalidator alias to ensure that the attribute appears in a subscribed list of values . 
Le The alias of the Ngth:cstringvalidator ensures that the length of the attribute .  the alias of the
Match:cregularexpressionvalidator within the specified range, ensuring that the attribute matches a regular expression .  The alias for the br> Numerical:cnumbervalidator ensures that the attribute is a valid numeric . 
Required:crequiredvalidator alias, ensuring that the attribute is not empty . 
Ty Pe:ctypevalidator alias to ensure that the attribute is .  the
Unique:cuniquevalidator alias for the specified data type, ensuring that the attribute is unique in the Data table field . 
Url:curlv The alias for the Alidator ensures that the attribute is a valid path.

Basically, it's more comprehensive and generally enough, but sometimes some of the validation needs to be customized. Take the above code as an example, we need to check whether the system already exists before the tag, if there is no user to add. This needs to be added before the query database to see if the tag already exists, here we need to customize a validation rule.

The key is two steps:

1. Add code in Rules: Array (' tagname ', ' checktagname ', ' on ' => ' create,update '),//check whether the tag is already present when inserting tag

Note: I used ' on ' => ' create,update ', so this validation rule takes effect on the create,update scene

2. Add validation functions to the model (models):

Public Function Checktagname ($attribute, $params) { 
  $oldtag = Tag::model ()->findbyattributes (Array (' tagname ' = > $this->tagname)); 
  if ($oldtag->tagid > 0) { 
    $this->adderror ($attribute, ' the tag already exists! '); 
   

One of the things that needs to be explained is:

(1) The parameters of the validation function must be ($attribute, $params) and cannot be missing any of them;

(2) $this->adderror ($attribute, ' the tag already exists! '); This is the error message you want to output in the view.

It's as simple as that, with this approach, the various rules of form validation can be customized.

Let me introduce you to yii custom validation rules

The simplest way to define a validation rule is to use its model internal definition.

For example, you want to check if the user's password is safe enough.

Normally you will use the Cregularexpression method validation, but for this guide we assume that there is no such validation method.

First, add two constants to the model

Const WEAK = 0;
Const STRONG = 1; Then set in the rules method of the model:

/**
 * @return Array validation rules for model attributes.
 */Public
function rules ()
{return Array (
    ' password ', ' passwordstrength ', ' Strength ' => Self::strong),
  );
}

Make sure that you write a rule that is not an existing rule, or you will report an error.

The way to do this is to create a method (i.e. passwordstrength) in the model that is called a rule named above.

/**
 * Check if the user password is strong enough
 * Check the password against the pattern requested
 * by the Strength Parameter
 * is the ' passwordstrength ' validator as declared in rules ().
 */Public
function Passwordstrength ($attribute, $params)
{
  if ($params [' strength '] = = self::weak)
    $ Pattern = '/^ (? =.*[a-za-z0-9]). {5,}$/'; 
  ElseIf ($params [' strength '] = = = Self::strong)
    $pattern = '/^ (? =.*\d)) (? =.*\d] (? =.*[a-za-z])). { 5,}$/'; 
    
  if (!preg_match ($pattern, $this-> $attribute))
   $this->adderror ($attribute, ' Your password is not strong Enough! ');
}

The method you just created requires two parameters: * $attribute properties that need to be validated * $params parameters that are customized in the rule

In the rules method of the model we validate the password property, so the property value that needs to be validated in the validation rule should be password.

In the Rules method we also set the custom parameter strength, and its value will be placed in the $params array.

You will find that in the method we use the Cmodel::adderror ().

Adding an error accepts two parameters: the first parameter is the error message that appears when the property name of the error is displayed in the form, and the second argument.

Complete method: Inherit Cvalidator class

If you want to use the rule in multiple models (model), the best way is to inherit the Cvalidator class.

Inheriting this class you can use like Cactiveform:: $enableClientValidation (Yii 1.1.7 version available) similar to other features.

To create a class file

The first thing to do is to create a class file. The best way to do this is to use the deferred load (lazy loading) feature of Yii when the class has the same filename and class name.

Let's create a new folder under the extended (extensiions) directory of the Application (application) (under the Protected folder).

Name the directory as: myvalidators

Then create the file: passwordstrength.php

To create our authentication method in a file

Class Passwordstrength extends Cvalidator
{public
  $strength;
  Private $weak _pattern = '/^ (? =.*[a-za-z0-9]). {5,}$/';
  Private $strong _pattern = '/^ (? =.*\d (? =.*\d)) (? =.*[a-za-z] (? =.*[a-za-z])). {5,}$/';
...
}

Create a property in a class that is a parameter that is used in a validation rule.

Cvalidator will automatically populate these properties based on parameters.

We have also created two other properties, which are regular expressions used by the Preg_match function.

Now we should rewrite the abstract methods of the parent class (abstract method) ValidateAttribute

/**
 * Validates the attribute of the object.
 * If There is any error, the error message is added to the object.
 * @param Cmodel $object The object being validated
 * @param string $attribute the attribute being validated
 */
   
    protected function ValidateAttribute ($object, $attribute)
{
  //Check the strength parameter used in the Validation rule of our model
  if ($this->strength = = ' weak ')
   $pattern = $this->weak_pattern;
  ElseIf ($this->strength = = ' strong ')
   $pattern = $this->strong_pattern;
  Extract the attribute value from it ' s model object
  $value = $object-> $attribute;
  if (!preg_match ($pattern, $value))
  {
    $this->adderror ($object, $attribute, ' Your password is too weak! ');
}
   

I don't think it's necessary to explain the above method. Of course you can also use constants in the condition of if, I recommend using.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.