PHP完全自学手册(珍藏版) 中文pdf扫描版下载
//控制器页面
//Instantiate the model class
$model = new \app\models\MyForm();
// populate model attributes with user inputs
$model->load(\Yii::$app->request->post());
//validate the date being submitted the end user
if ($model->validate()) {
// all inputs are valid
} else {
// validation failed, we can access the errors using $error property as:
$errors = $model->errors;
}
//验证处理
use yii\base\Model;
class MyForm extends Model
{
public $username;
public $email;
public function rules()
{
return [
// an inline validator defined as the model method validateUsername()
['username', 'validateUsername'],
// an inline validator defined as an anonymous function
['email', function ($attribute, $params) {
if (!filter_var($this->$attribute, FILTER_VALIDATE_EMAIL)) {
$this->addError($attribute, 'The email format is invalid!');
}
}],
];
}
public function validateUsername($attribute, $params)
{
if (preg_match('/[^a-z])/i', $this->$attribute)) {
$this->addError($attribute, 'Username should only contain alphabets');
}
if ( ! preg_match('/^.{3,8}$/', $this->$attribute) ) {
$this->addError($attribute, 'Username must be bwtween 3 to 8 characters.');
}
}
}
转载请注明:谷谷点程序 » yii 表单高级验证