php--yii框架表单验证

在视图层利用表单小部件生成表单时,field只能是数据库中存在的, 例如:

use yii\helpers\Html;

use yii\widgets\ActiveForm;

use yii\captcha\Captcha;

其中,确认密码和验证码等字段我们是不需要在数据库中设计的,这时,需要在模型层定义相应的属性:

public $repassword;

public $userimg;

public $captcha;

public $phone;

在模型层定义验证规则rules:

public function rules()

{

  return [

    [['username', 'password', 'repassword', 'captcha', 'age', 'sex', 'phone','email'], 'filter', 'filter'=>'trim', 'on'=>'register'],

    [['username', 'password', 'repassword', 'captcha', 'age', 'sex', 'phone','email'], 'required', 'message'=>'{attribute}不能为空'],

    [['username'], 'match', 'pattern'=>'/^\w{6,20}$/', 'message'=>'{attribute}为6-20位数字字母或下划线'],

    //['username', 'unique', 'targetClass' => '\common\models\User', 'message' => 'This username has already been taken.'],

    //[['age'], 'number', 'integerOnly'=>true, 'max'=>150, 'min'=>18, 'tooBig'=>'{attribute}只能是18-150以内整数', 'tooSmall'=>'{attribute}只能是18-150以内整数'],

    [['password'], 'match', 'pattern'=>'/^[a-z_]\w{5,19}$/', 'message'=>'{attribute}为6-20位数字字母或下划线,不能以数字开头'],

    ['repassword', 'compare', 'compareAttribute'=>'password', 'message'=>'两次输入密码不一致'],

    ['sex', 'in', 'range'=>['男', '女'], 'message'=>'{attribute}只能是男或女'],

    [['phone'], 'match', 'pattern'=>'/^(13|15|18)[0-9]{9}$/', 'message'=>"{attribute}只能是13,15,18开头的11位数字"],

    //['phone', 'checkPhone'], [['email', 'userimg'], 'string', 'max' => 50], ['email', 'email'], //['email', 'unique'],

    ['userimg', 'file', 'skipOnEmpty'=>false, 'extensions'=>'png,jpg,gif'],

    ['captcha', 'captcha', 'message'=>'请输入正确地{attribute}','captchaAction'=>'usermessage/captcha'],

   ];

}

解析:

    Filter: 过滤,'filter'=>'trim',表示去空格

    Required:必须的,表示不能为空

    Match: 匹配正则,需要和pattern一起使用,定义正则表达式,

    'pattern'=>'/^\w{6,20}$/',

    Unique:验证数据唯一性,在注册时用到的比较多,这里需要注意的是,在rules规则里面定义的唯一性验证,只有在服务器端才能验证,如果想要在表单页面显示,需要开启”enableAjaxValidation”=>ture;

    例如:

    'sign-form', //'enableAjaxValidation' => true,//启用ajax验证,

    将属性值发送到服务器端进行验证并返回结果,默认为false 'enableClientValidation' => true,//启用客户端验证,默认值为true,关闭后表单无js验证

     'options'=>['action'=>'usermessage/signform', 'method'=>'post', 'enctype'=>'multipart/form-data']]); ?>

    这里需要注意的是,在这里启用的话,ajax验证是作用于所有的属性的,所以,还有另一种开启方式,在某一个field里面开启:

    field($model, 'username', ['enableAjaxValidation'=>true])->textInput() ?>

    ,这样就单独作用于username属性了。 要想实现表单ajax验证唯一性,后台还要一个ajax判断:

    $model->load(Yii::$app->request->post());

    if (Yii::$app->request->isAjax)

      {

        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

        return \yii\bootstrap\ActiveForm::validate($model);

       } 在有数据提交时,最好先执行$model->load(Yii::$app->request->post()); 操作,不要做多余的处理,然后判断ajax,否则ajax验证的时候可能会报错500。    如果有验证码,这里就会有另一个问题:return \yii\bootstrap\ActiveForm::validate($model);这个验证的是所有的属性,而验证码执行validate后就会重新生成,那么在表单提交时我们进行数据有效性验证时就会报错,

    解决方式:\yii\bootstrap\ActiveForm::validate()这个方法其实是有两个参数的,$model,$attributes,我们可以指定ajax验证某一些特定的属性,写法是:\yii\bootstrap\ActiveForm::validate($model, ['username', 'email', 'phone']);这样ajax验证时就只验证username,email,phone这三个字段了,不会影响验证码。         Number:数字验证,加上'integerOnly'=>true,表示只能是整数,max,min分别表示最大最小值,tooBig和tooSmall分别是超过最大值和低于最小值时的错误提示信息     

    Compare:比较,用于两个属性之间的比较,'compareAttribute'=>'password',表示与password比较 In:和range连用,定义范围,表示属性值必须在这个范围内,通常用于验证某些固定值 Email:邮箱验证 File:文件验证 extensions可以定义上传文件的类型 Captcha:

    验证码验证,需要定义生成验证码的方法,'captchaAction'=>'usermessage/captcha',usermessage表示控制器名,captcha表示方法名 可以在控制器层定义一个actions方法添加captcha方法:

    /** * 生成验证码的方法 */

    public function actions() {

      parent::actions();

      return [ 'captcha' => [ 'class' => 'yii\captcha\CaptchaAction', //'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null, 'maxLength' => 3, 'minLength' => 3 ], ];

    }

    每一个验证都可以添加应用场景:’on’=>’register’; 在控制器层实例化模型层 $model = new Usermessage(); $model->setScenario('register'); 定义使用应用场景为register 在模型层需要定义场景作用的对象

    /** * 定义验证场景 */

    public function scenarios() {

      return [ 'register' => ['username', 'password', 'repassword', 'age', 'sex', 'phone','email'], 'login' => ['username', 'password','age', 'sex', 'phone','email'], ];

    }

    然后在对应的验证规则后面限定应用场景’on’=>’register’; 当表单验证时,为在作用场景以内的参数可以不受验证规则的限制 添加入库:复选框因提交过来后是一个数组,所以在执行save()前需要将复选框的值处理成字符串