目录
根据经验,您永远不应该相信从最终用户那里收到的数据,并且应该在很好地使用这些数据之前对其进行验证。
给定一个model模型,用户输入填充后,您可以通过调用yii\base\Model::validate()方法。该方法将返回一个布尔值,指示验证是否成功。否则,您可能会从?yii\base\Model::$errors?获取错误信息。举个例子,
$model = new \app\models\ContactForm();
// 接收到的参数
$model->load(\Yii::$app->request->post());
// 其等效于以下内容
// $model->attributes = \Yii::$app->request->post('ContactForm');
if ($model->validate()) {
// 所有验证通过
} else {
// 验证失败:$errors是一个包含错误消息的数组
$errors = $model->errors;
}
public function rules()
{
return [
// the name, email, subject and body attributes are required
[['name', 'email', 'subject', 'body'], 'required'],
// the email attribute should be a valid email address
['email', 'email'],
];
}
?有时候你需要做特殊验证对于未绑定到任何模型的值。
如果您只需要执行一种类型的验证(例如验证电子邮件地址),您可以调用验证()方法,如下所示:
$email = 'test@example.com';
$validator = new yii\validators\EmailValidator();
if ($validator->validate($email, $error)) {
echo 'Email is valid.';
} else {
echo $error;
}
<?php
/**
* @author zhao
* @copyright Copyright (c) 2018 HNBY Network Technology Co., Ltd.
* @wx zzoood
*/
namespace api\modules\models;
use Yii;
use yii\base\Exception;
use yii\base\Model;
use yii\base\UserException;
class WeLoginForm extends Model
{
public $mobile;
//手机区号
public $uid;
public $sms_code;
public $invite_code;
public function rules() {
return [
[['mobile', 'sms_code', 'invite_code'], 'trim'],
[['mobile', 'code', 'invite_code'], 'string'],
['mobile', 'validateMobile'],
['invite_code', 'validateInviteCode', 'skipOnEmpty' => false],
['sms_code', 'validateSmsCode'],
];
}
public function attributeLabels() {
return [
'mobile' => '手机号',
'sms_code' => '短信验证码',
'invite_code' => '推荐码',
];
}
public function validateMobile($attribute) {
if (!$this->hasErrors()) {
if (!Utils::isMobile($this->mobile, $this->countryCode)) {
$this->addError($attribute, '手机号格式不对');
}
}
}
public function validateSmsCode($attribute) {
if (!$this->hasErrors()) {
try {
SmsVerifycode::check($this->biz_id, 'bind', $this->mobile, $this->sms_code);
} catch (Exception $e) {
$this->addError($attribute, $e->getMessage());
}
}
}
public function validateInviteCode($attribute)
{
if (!$this->hasErrors()) {
if ($this->getMobileUser()) {
// 登录时和绑定已存在的手机号时不验证
return;
}
//锁粉记录存在时不验证
if (!empty($this->uid)) {
$user = User::findOne($this->uid);
if (!empty($user) && !empty($user->wechat_unionid)) {
$wxlock = Wxlock::find()->where(['biz_id' => $this->biz_id, 'wechat_unionid' => $user->wechat_unionid])->one();
if (!empty($wxlock)) {
return;
}
}
}
$mustInviteCode = DistributionConfig::get($this->biz_id, 'user-config', 'INVITE_IS_OPEN', 0);
if ($mustInviteCode) {
if (!$this->invite_code) {
$this->addError($attribute, '请填写邀请码');
}
}
}
}
}
?内联验证器是根据模型方法或匿名函数定义的。方法/函数的签名是:
use yii\base\Model;
class MyForm extends Model
{
public $country;
public $token;
public function rules()
{
return [
// an inline validator defined as the model method validateCountry()
['country', 'validateCountry'],
// an inline validator defined as an anonymous function
['token', function ($attribute, $params, $validator) {
if (!ctype_alnum($this->$attribute)) {
$this->addError($attribute, 'The token must contain letters or digits.');
}
}],
];
}
public function validateCountry($attribute, $params, $validator)
{
if (!in_array($this->$attribute, ['USA', 'Indonesia'])) {
$this->addError($attribute, 'The country must be either "USA" or "Indonesia".');
}
}
}
/**
* 商品检索
*/
public function actionProductSearch(){
$request = Yii::$app->request;
try {
$model = new DouForm();
$model->load($request->post(),'');
if (!$model->validate()) {
throw new Exception($this->errors($model->errors));
}
} catch (Exception $e) {
return $this->responseJson(1, '', $e->getMessage());
}
}
<?php
/**
* @author zhao
* @copyright Copyright (c) 2018 HNBY Network Technology Co., Ltd.
* @wx zzoood
*/
namespace api\modules\models;
use yii\base\Model;
class DouForm extends Model
{
public $title;
public $num;
public function rules() {
return [
['title', 'required'],
['num', 'integer', 'min' => 0, 'max' => 1],
];
}
public function attributeLabels() {
return [
'title' => '标题',
'num' => '数量',
];
}
}
// 因errors是一个数组,不能有效的返回给前端错误信息,进行改造
/**
* 验证类错误处理
*/
public function errors($errors){
foreach ($errors as $error) {
return $error[0];
}
exit();
}