Error code with model validation errors

How can I add error code with validation errors.

When the validation of attributes fail by $model->validate(), we can see the errors through $model->getErrors() function, which shows the attributes with respective error messages. But i want to distinguish between ‘required’ validation errors, ‘max’/‘min’ errors, ‘integer’ type errors etc.

This can be achieved in laracast apparently (see link below). But how can we achieve this in Yii 2

Thanks in advance


You can add error messages with:

$model->addError(‘attribute’, ‘My error message’);

Take a look at:

Best Regards

I am not asking about editing a default message content on validation error which is [message: message content], instead I want to pass another key-value pair like [error code: error code value]

For what reason do you want to distinguish the errors using "error codes"? What is the use case?

To me, the error messages like “xxx is required.” and “Oh!, you’ve forgot to input xx.” seems fairly enough for the end users. They don’t need to read the “error code”.


If you do need to use the error code, you have to customize the error messages to suit your needs.



"E101:The attribute is required."