我试图使yii2验证我的ActiveForm字段,该字段应该是数字的,长度为8个字符。
下面是我在默认的LoginForm模型yii2/advanced/backend中尝试过的,但不幸的是,isNumeric验证器根本没有启动:
public function rules()
{
return [
// username and password are both required
[['username', 'password'], 'required'],
// username should be numeric
['username', 'isNumeric'],
// username should be numeric
['username', 'string', 'length'=>8],
// password is validated by validatePassword()
['password', 'validatePassword'],
];
}
/**
* Validates if the username is numeric.
* This method serves as the inline validation for username.
*
* @param string $attribute the attribute currently being validated
* @param array $params the additional name-value pairs given in the rule
*/
public function isNumeric($attribute, $params)
{
if (!is_numeric($this->username))
$this->addError($attribute, Yii::t('app', '{attribute} must be numeric', ['{attribute}'=>$attribute]));
}
/**
* Validates the password.
* This method serves as the inline validation for password.
*
* @param string $attribute the attribute currently being validated
* @param array $params the additional name-value pairs given in the rule
*/
public function validatePassword($attribute, $params)
{
if (!$this->hasErrors()) {
$user = $this->getUser();
if (!$user || !$user->validatePassword($this->password)) {
$this->addError($attribute, 'Incorrect username or password.');
}
}
}我还尝试添加一个相关帖子(https://stackoverflow.com/a/27817221/2037924)中所建议的场景,但如果我没有在场景中包含password字段,这只起作用(如显示错误)。
这是一个很好的方法来实现这一点,或者你能想出一个更好的方式去做吗?
注:,我将username定义为string的原因是,数字可能包含前导0。
发布于 2015-10-11 23:55:12
在这里阅读更多关于验证的信息:http://www.yiiframework.com/doc-2.0/guide-tutorial-core-validators.html#number
这对我来说很好,使用了来自yii2 2-basic的联系方式。
/**
* @return array the validation rules.
*/
public function rules()
{
return [
// name, email, subject and body are required
[['name', 'email', 'subject', 'body'], 'required'],
// email has to be a valid email address
['email', 'email'],
['subject', 'is8NumbersOnly'],
// verifyCode needs to be entered correctly
['verifyCode', 'captcha'],
];
}
public function is8NumbersOnly($attribute)
{
if (!preg_match('/^[0-9]{8}$/', $this->$attribute)) {
$this->addError($attribute, 'must contain exactly 8 digits.');
}
}发布于 2015-10-12 04:06:03
尝试使用integer数据类型:
[['username'], 'integer'],
[['username'], 'string', 'min' => 8],它将同时验证numeric和length。这就行了。
发布于 2016-08-29 17:00:03
public function rules()
{
return [
// username should be numeric
['username', 'match', 'pattern' => '/^\d{8}$/', 'message' => 'Field must contain exactly 8 digits.],
// ...
];
}https://stackoverflow.com/questions/33071345
复制相似问题