As 'exist' is used for availability, the 'unique' validator checks to see if the input value in a table column is unique.
As before targetClass, targetAttribute, filter is valid for unique.
Note: It only works with Active Record model attributes
But you can also use the following methods:
Inline Validators:
return [
['identitynumber', 'unique',
'targetClass' => Deathregister::className(),
'targetAttribute' => ['nationalidnum' => 'idnum'],
'message'=>'The ID number Supplied Belongs to the Dead'
/*Also, if validation of one attribute depends on the value of another attribute */
// 'when' => function ($model) {
// if (condition) {
// return $this->addError('identitynumber', Yii::t('user', 'The ID number Supplied Belongs to the Dead'));
// }
// return false;
// }
],
];
Example2:
return [
// validatorMethod()
['identitynumber', 'validatorMethod'],
// or
['identitynumber', function ($attribute, $params) {
if(!Deathregister::findOne(['nationalidnum' => $this->$attribute])->exists()) {
$this->addError($attribute, 'The ID number Supplied Belongs to the Dead.');
}
}],
];
// validatorMethod()
public function ValidatorMethod($attribute, $params)
{
if(!Deathregister::findOne(['nationalidnum' => $this->$attribute])->exists()) {
$this->addError($attribute, 'The ID number Supplied Belongs to the Dead');
}
}
/** Or */
// public function validatorMethod()
// {
// if(!Deathregister::findOne(['nationalidnum' => $this->identitynumber])->exists())
# code ...
// }
// }
You can also extend the class (Standalone Validators)
It is better to refer to this page and this page.
Link2
Note:If you want to make sure a rule is always applied, you may configure the skipOnEmpty and/or skipOnError properties to be false in the rule declarations.