Description
Description
Currently there seems to be no easy way for custom translations of error messages with constraints as described in #169
The ValidationError
interface already contains enough information to create custom translation keys such as validation.min
but is missing the actual constraint metadata which is required in order to fully translate or customize a validation error message.
To get the additional metadata we currently need to either use the context
option in all of our decorators and redundantly pass the constraints as context, or wrap all available decorators in custom decorators and automatically pass the constraints as context as described in #169 (comment)
If we could access the constraint metadata in the ValidationError by default, it would heavily simplify this use-case as in the following example.
Example
Lets assume this is my translation file:
{
"validation.max": "{property} must be less or equal to {constraint1}"
}
My custom translation function looks something like this:
interface ErrorMetadata {
property: string;
type: string;
message: string;
metadata: { constraints: any[] }
context: any;
}
const translateError = (error: ErrorMetadata) => {
const translationKey = `validation.${error.type}`;
const translatedProperty = translate(`myform.properties.${error.property}`);
// instead of hardcoded translation options
// we could auto generate translation options form property and constraints
return translate(translationKey, {
property: translatedProperty,
constraint1: error.metadata.constraints[0]
});
}
const getFirstError(error: ValidationError): ErrorMetadata {
// Determine the first error and map to ErrorMetadata format
}
const validationErrors = validate(loginModel);
// Get first error and prepare it to be usable in translate function above
const firstErrors = validationErrors.map(getFirstError);
const errors = firstErrors.map((error) => { property: error.property, message: translateError(error) } )
Proposed solution
The following branch includes such a change develop...buddh4:class-validator:feature/include-validation-metadata-to-validationerror
Maybe there should be a validation and/or global setting to opt-in to this behavior in order to not change the current ValidationError output.
If this feature and solution is of interest, I could keep working on this change.
Another solution
Another solution for this problem would simply adding an additional ValidatorOptions
option e.g. transformMessage
which is used to generate the message e.g. here https://github.com/typestack/class-validator/blob/develop/src/validation/ValidationExecutor.ts#L407