yii框架中验证器声明一组内置验证器可以使用短名称引用
1.内置验证器的短名称分别有:
boolean
: yii\validators\BooleanValidator
captcha
: yii\captcha\CaptchaValidator
compare
: yii\validators\CompareValidator
date
: yii\validators\DateValidator
default
: yii\validators\DefaultValueValidator
double
: yii\validators\NumberValidator
each
: yii\validators\EachValidator
email
: yii\validators\EmailValidator
exist
: yii\validators\ExistValidator
file
: yii\validators\FileValidator
filter
: yii\validators\FilterValidator
image
: yii\validators\ImageValidator
in
: yii\validators\RangeValidator
integer
: yii\validators\NumberValidator
match
: yii\validators\RegularExpressionValidator
required
: yii\validators\RequiredValidator
safe
: yii\validators\SafeValidator
string
: yii\validators\StringValidator
trim
: yii\validators\FilterValidator
unique
: yii\validators\UniqueValidator
url
: yii\validators\UrlValidator
ip
: yii\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 }