Marcelo de Andrade Marcelo de Andrade - 2 months ago 6
PHP Question

How to use many custom validators in same field

In the same field I have two possible types of data:

CPF
and
CNPJ
. I'm using a custom component for validations individually, like:

['cnpj', CnpjValidator::className(), 'skipOnError' => true]


or

['cpf', CpfValidator::className(), 'skipOnError' => true]


but I tried using the two classes for the same field
cnpj_cpf
and it didn't succeeded. The rules will be applied individually based on the
natureza
attribute that belongs to the same model.

something like:

if($model->natureza == 'F'){
// apply CpfValidator::className()
else {
// apply CnpjValidator::className()
}

Answer

You could try :

['cnpj_cpf', CnpjValidator::className(), 'skipOnError' => true, 'when' => function($model){
    return $model->natureza != 'F';
}],
['cnpj_cpf', CpfValidator::className(), 'skipOnError' => true, 'when' => function($model){
    return $model->natureza == 'F';
}],

Read more about Conditional Validation.