Add Error Codes For Validation Errors

In the current implementation you can very easily find out, if a validation error occurred on an attribute. But it’s very hard to find out programatically, which validation error it was. You have to parse an error message like “First name is too short (minimum is 30 characters)” to find out, that length validation failed. Situation gets worse if you customize your error messages and it’s almost impossible if you add translation through Yii::t().

Why could that be useful? Some examples:

  • You want to write an API for your app and want to give as much freedom to your client developers as possible. So they should decide, how to react on different validation errors

  • You want to write your own clientside validation logic in javascript. Different things should happen on different validation errors.

I think there are many more use cases of this.

I don’t have a clear idea about implementation. But here’s a first suggestion:

We could have getErrorCode($attribute) and getErrorCodes($attribute=null) methods in CModel. They would work much the same as getError and getErrors with the only difference, that they return something like CStringValidator::TOO_SHORT. That constant could be a verbose string like ‘string-too-short’ or ‘number-no-integer’. So the pattern could be ‘<validator>-<message>’.

What do you think?

Nice idea.

Meanwhile, prefixing the localized error message itself with a custom code helps achieving a correct result if I understand well what you intend to have. When dealing with custom validation JS or serving app through an API, the clients would expect a <code> <some special agreed character> <localized error message to display as is if needed>. Just saying :)

If i prefix the validation messages, then this also appears on the regular web pages. That’s not what i want. And i’d consider this a bit of a hack. :) We should have a proper solution.

Hi Mike,

Are you able to find a solution to support error codes? or the only way is as you suggested above