yii2表单验证方法

model层的书写验证规则

return
[
[['username','password','email','phone','images'],'required','message'=>'不能为空'],
//验证唯一性
[['username'], 'unique','targetClass' => '\backend\models\Verification','message'=>'用户名不能一致'],
//验证长度
['username', 'string', 'min' => 2, 'max' => 8,"tooLong"=>"太长了", "tooShort"=>"太短了"],
//正则验证
['username','match','pattern'=>'/^[a-z]{1,}$/','message'=>'用户名必须为字母'],
['password','match','pattern'=>'/^[0-9]{6,12}$/','message'=>'密码必须是数字,且大于6为小于12位'],
['email', 'unique', 'targetClass' => '\backend\models\Verification', 'message' => '邮箱名已存在.'],
//邮箱验证
['email','match','pattern'=>'/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/','message'=>'邮箱格式不正确'],
//手机号验证
['phone','match','pattern'=>'/^1[0-9]{10}$/','message'=>'手机号格式不正确'],



   ];


视图层代码

 'login-form',
    'options' => ['class' => 'form-horizontal'],
]) ?>
    field($model, 'username')->label('用户名') ?>
    field($model, 'password')->passwordInput()->label('密码') ?>
    field($model, 'email')->label('邮箱') ?>
    field($model, 'phone')->label('手机号') ?>


    
'btn btn-primary']) ?>



控制器层
function actionAdd()
{
$model = new AddForm();
//是否通过验证,接受数据
if ($model->load(\Yii::$app->request->post()) && $model->validate())
{
echo "asdfdas";die;
            return $this->redirect(['view', 'id' => $model->id]);
        } 
        else 
        {
            return $this->render('add', [
                'model' => $model,
            ]);
        }
}



表单验证:http://www.kuitao8.com/20140425/2334.shtml

你可能感兴趣的:(php)