官网说得非常的详细
基础篇:
https://www.yiichina.com/doc/guide/2.0/input-validation
高级篇:
https://www.yiichina.com/doc/guide/2.0/tutorial-core-validators
<?php
namespace app\modules\msg\validate\im;
use yii\base\Model;
class TestValidate extends Model
{
public $country;
public $token;
public $bianliang;
public $papi;
public $password;
public $password_repeat;
public $age;
public $phone;
public function rules()
{
return [
// 定义为模型方法 validateCountry() 的行内验证器required
['papi', 'required', 'on' => 'add'],
['mobile', 'exist', 'targetClass' => 'xmobile\modules\v1\models\BuyerList', 'message' => '当前用户不存在','on'=>['forgetpassword']],
['mobile', 'exist', 'targetClass' => 'xmobile\modules\v1\models\BuyerList', 'message' => '当前用户不存在','on'=>['forgetpassword']],
['mobile', 'unique', 'targetClass'=>'xmobile\modules\v1\models\BuyerList','message' => '此用户名已经被使用','on'=>['Inserbuyer']],
[['password'],'match','pattern'=>'/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,12}$/','message' => '密码是字母和数字组成'],
[['company'],'match','pattern'=>'/^[\x{4e00}-\x{9fa5}A-Za-z0-9]+$/u','message'=>'公司名称必须是中文 字母 数字'],
['mobile', 'unique', 'targetClass'=>'xmobile\modules\v1\models\BuyerList','message' => '此用户名已经被使用','on'=>['Inserbuyer']],
[['password'],'match','pattern'=>'/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,12}$/','message' => '密码是字母和数字组成'],
[['company'],'match','pattern'=>'/^[\x{4e00}-\x{9fa5}A-Za-z0-9]+$/u','message'=>'公司名称必须是中文 字母 数字'],
['password', 'compare', 'message' => '密码不一样'],
['age', 'compare', 'compareValue' => 30, 'operator' => '>', 'message' => '年龄必须大于30岁'],
//手机验证
['mobile','match','pattern'=>'/^[1][34578][0-9]{9}$/'],
['country', 'validateCountry', 'on' => 'test'],
// ['fromDate', 'compare', 'compareAttribute' => 'toDate', 'operator' => '<', 'enableClientValidation' => false], //日期对比
// 定义为匿名函数的行内验证器
['token', function ($attribute, $params) {
if (!ctype_alnum($this->$attribute)) {
$this->addError($attribute, 'The token must contain letters or digits.');
}
}],
//默认值
['bianliang', 'default', 'value' => 'wo shi bianliang'],
// [['from', 'to'], 'default', 'value' => function ($model, $attribute) {
// return date('Y-m-d', strtotime($attribute === 'to' ? '+3 days':'+6 days'));
// }],
//循环验证 必须为数组
// [
// // 检查是否每个分类编号都是一个整数
// ['categoryIDs', 'each', 'rule' => ['integer']],
// ],
['phone', 'filter', 'filter' => function ($value) {
// 在此处标准化输入的电话号码
$value = $value.'我是添加的手机号码';
return $value;
}],
//范围 in 的使用
// [
// // 检查 "level" 是否为 1、2 或 3 中的一个
// ['level', 'in', 'range' => [1, 2, 3]],
// ]
//正则表达式
// [
// // 检查 "username" 是否由字母开头,且只包含单词字符
// ['username', 'match', 'pattern' => '/^[a-z]\w*$/i']
// ]
//字符长度
// [
// // 检查 "username" 是否为长度 4 到 24 之间的字符串
// ['username', 'string', 'length' => [4, 24]],
// ]
// 值在数据表中已存在
['email', 'exist', 'targetClass' => 'commonmodelsUser', 'filter' => ['status' => User::STATUS_ACTIVE], 'message' => 'There is no user with such email.']
// 值在表中的唯一性
['email', 'unique', 'targetClass' => 'commonmodelsUsers']
];
}
/**
*
* 验证方法
* @param $attribute
* @param $params
* @return string
*/
public function validateCountry($attribute, $params)
{
if (!in_array($this->$attribute, ['USA', 'Web'])) {
$this->addError($attribute, 'The country must be either "USA" or "Web".');
}
return '中国';
}
/**
* 场景
* @return array
*/
public function scenarios()
{
return [
'token'=>['token']
];
}
}
controller 中的使用
public function actionTest(){
$model = new TestValidate();
$model->setAttributes(\Yii::$app->request->post(),false);
$model->setScenario('token');
if(!$model->validate()){
$this->error(CommonService::getModelError($model->errors));
}
echo $model->phone;
}
临时验证:
方法1:
public function actionSearch($name, $email)
{
$model = DynamicModel::validateData(compact('name', 'email'), [
[['name', 'email'], 'string', 'max' => 128],
['email', 'email'],
]);
if ($model->hasErrors()) {
// 验证失败
} else {
// 验证成功
}
}
方法2:
public function actionSearch($name, $email)
{
$model = new DynamicModel(compact('name', 'email'));
$model->addRule(['name', 'email'], 'string', ['max' => 128])
->addRule('email', 'email')
->validate();
if ($model->hasErrors()) {
// 验证失败
} else {
// 验证成功
}
}
参考:https://www.cnblogs.com/imxiu/p/4959850.html