yii2中的rules 自定义验证规则详解,yii2rules
yii2中的rules 自定义验证规则详解,yii2rules
yii2的一个强大之处之一就是他的Form组件,既方便又安全。有些小伙伴感觉用yii一段时间了,好嘛,除了比tp"难懂"好像啥都没有。
领导安排搞一个注册的功能,这家伙刷刷刷的又是百度啥啥啥好的表单样式,又是百度啥啥啥validate验证,真替这家伙捏把汗。
当然啦,废话说在前头,咱们的重点喃,是要利用ActiveForm,然后怎么去实现自定义验证规则。
先来说说场景:
条件:①、有两个字段分别是A和B ②、A有两个值分别是1和2
需求是:当用户选择的A的值等于1的时候,B的值必须填写,当A的值等于2的时候,B的值不写也没关系。其中A必选。
我们来看看用Yii2自带的rules怎么去实现
首先在其关联model上加上下面这句规则
/** * @inheritdoc */ public function rules() { return [ [['B'], 'requiredByASpecial'], ]; }
然后在该model里面去实现requiredByASpecial方法即可
/** * 自定义验证B */ public function requiredByASpecial($attribute, $params) { if ($this->A== 1) { if ($this->B=== '') $this->addError($attribute, "B的值不可以为空."); } }
上面的意思就是说当A等于1且B的值为空时,返回错误信息"B的值不可以为空"。
以上只是举了一个简单的例子,可以根据具体需求应用。
以上所述是小编给大家介绍的yii2 rules 验证规则的全部内容,希望对大家有所帮助!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

