LoginForm:
public function rules()
{
return [
// username and password are both required
[['username', 'password'], 'required'],
// username should be a number and of 8 digits
[['username'], 'number', 'message'=>'{attribute} must be a number'],
[['username'], 'string', 'length' => 8],
// password is validated by validatePassword()
['password', 'validatePassword'],
];
}
/**
* 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.');
}
}
}
I have set up 2 rules for the same field as you can see above:
[['username'], 'number', 'message'=>'{attribute} must be a number'],
[['username'], 'string', 'length' => 8],
I would like the form to display different error messages for the following 3 scenarios situations:
- The provided value is neither a number, nor 8 characters (digits).
- The provided value is a number, but is not of 8 characters (digits).
- The provided value is not a number, but is of 8 characters (digits).
My question is 2 fold:
A. Is there a way to combine these rules in any standard, Yii2
way.
B. In my previous question I have tried to set up a custom validator (the obvious way to solve this), but it was very simply ignored. The only way I could make it validate was if I added the username
field to a scenario. However, once I added password
too, it was again ignored. Any reason's for this that you can think of? EDIT: skipOnError = false
changed nothing at all in this behaviour.
So please, when you answer, make sure you test it preferably in yii2/advanced
; I barely touched the default set up, so it should be easy to test.
EDIT: for clarity, I would like to only allow numbers that are of 8 characters (digits), so they can potentially have a leading 0
, eg. 00000001
, or 00000000
for that matter. This is why it has to be a numeric string.