Marcelo de Andrade Marcelo de Andrade - 1 year ago 81
PHP Question

How to use many custom validators in same field

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

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

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


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

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

something like:

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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download