yii2 rules验证规则,ajax验证手机号码是否唯一
Posted 岁月如歌
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了yii2 rules验证规则,ajax验证手机号码是否唯一相关的知识,希望对你有一定的参考价值。
<?php namespace frontend\models; use Yii; use yii\base\Model; /** * Signup form */ class SignupForm extends Model { public $mobile; public $captcha; public $password; /** * @inheritdoc */ public function rules() { return [ [[‘mobile‘, ‘captcha‘, ‘password‘], ‘trim‘], [[‘mobile‘, ‘captcha‘, ‘password‘], ‘required‘], [[‘mobile‘], ‘match‘, ‘pattern‘ => ‘/^1[3|4|5|7|8][0-9]{9}$/‘], [[‘mobile‘], ‘unique‘, ‘targetClass‘ => ‘\common\models\User‘, ‘message‘ => ‘该手机号已被注册!‘], [[‘password‘], ‘match‘, ‘pattern‘ => ‘/^\S+$/‘], [[‘password‘], ‘string‘, ‘length‘ => [6, 32]], [[‘captcha‘], ‘captcha‘], ]; } /** * @inheritdoc */ public function attributeLabels() { return [ ‘mobile‘ => ‘手机号‘, ‘captcha‘ => ‘验证码‘, ‘password‘ => ‘密码‘ ]; } public function writeSession() { $session = Yii::$app->session; $session->open(); $session[‘mobileSignupTimeout‘] = time() + 600; $session[‘mobileSignup‘] = $this->mobile; $session[‘mobileSignupPassword‘] = $this->password; } }
UserController.php
if ($step !== ‘2‘) { $model = new SignupForm(); $model->load(Yii::$app->request->post()); if (Yii::$app->request->isAjax) { Yii::$app->response->format = Response::FORMAT_JSON; return ActiveForm::validate($model); } if (Yii::$app->request->isPost && $model->validate()) { $model->writeSession(); if ($this->_sendMsg($model->mobile)) { Yii::info("用户注册发送短信验证码成功!手机号:{$model->mobile}"); Yii::$app->session->setFlash(‘sentSuccess‘); } else { Yii::warning("用户注册发送短信验证码失败!手机号:{$model->mobile},说明:" . Yii::$app->smser->message); Yii::$app->session->setFlash(‘failedToSend‘, ‘验证码发送失败,请您再试一次!‘); } return $this->redirect([‘signup‘, ‘step‘ => ‘2‘]); }
signup.php
if ($step !== ‘2‘) { $model = new SignupForm(); $model->load(Yii::$app->request->post()); if (Yii::$app->request->isAjax) { Yii::$app->response->format = Response::FORMAT_JSON; return ActiveForm::validate($model); } if (Yii::$app->request->isPost && $model->validate()) { $model->writeSession(); if ($this->_sendMsg($model->mobile)) { Yii::info("用户注册发送短信验证码成功!手机号:{$model->mobile}"); Yii::$app->session->setFlash(‘sentSuccess‘); } else { Yii::warning("用户注册发送短信验证码失败!手机号:{$model->mobile},说明:" . Yii::$app->smser->message); Yii::$app->session->setFlash(‘failedToSend‘, ‘验证码发送失败,请您再试一次!‘); } return $this->redirect([‘signup‘, ‘step‘ => ‘2‘]); }
以上是关于yii2 rules验证规则,ajax验证手机号码是否唯一的主要内容,如果未能解决你的问题,请参考以下文章