yii验证机制

7 篇文章 0 订阅
6 篇文章 1 订阅

官网说得非常的详细
基础篇:

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

廖圣平

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值