yii框架中验证器声明一组内置验证器可以使用短名称引用

1.内置验证器的短名称分别有:

  booleanyii\validators\BooleanValidator

  captchayii\captcha\CaptchaValidator

  compareyii\validators\CompareValidator

  dateyii\validators\DateValidator

  defaultyii\validators\DefaultValueValidator

  doubleyii\validators\NumberValidator

  eachyii\validators\EachValidator

  emailyii\validators\EmailValidator

  existyii\validators\ExistValidator

  fileyii\validators\FileValidator

  filteryii\validators\FilterValidator

  imageyii\validators\ImageValidator

  inyii\validators\RangeValidator

  integeryii\validators\NumberValidator

  matchyii\validators\RegularExpressionValidator

  requiredyii\validators\RequiredValidator

  safeyii\validators\SafeValidator

  stringyii\validators\StringValidator

  trimyii\validators\FilterValidator

  uniqueyii\validators\UniqueValidator

  urlyii\validators\UrlValidator

  ipyii\validators\IpValidator

2. 下面举个例子   

1 public function rules() {
2         return [
3             [['name', 'password', 'email'], 'required'],
4             ['name', 'unique', 'message'=>'{attribute}已经被占用'],
5             ['name', 'string', 'min'=>3, 'max'=>16, 'message'=>'{attribute}的长度必须在3~16之间'],
6             ['email', 'email', 'message'=>'请输入正确的{attribute}'],
7             ['password', 'string', 'min'=>8, 'max'=>16, 'message'=>'{attribute}的长度必须在8~16之间'],
8         ];
9     }

最后验证这些规则只需要用model调用validate()方法即可,例子如下:


 1 //将user对象保存到mongo数据库中
 2     public function saveUser($name, $password, $email) {
 3         $user = new User();
 4         $user->name = $name;
 5         $user->password = $password;
 6         $user->email = $email;
 7                 //在这里用$user调用yii\validators\Validatotr::validate()进行验证所有的属性
 8         if ($user->validate()) {
 9             $user->insert();
10         } else {
11             return $user->errors;
12         }
13     }

 

 

 

  

posted @ 2016-07-27 10:52  艾若菲  阅读(215)  评论(0编辑  收藏  举报