I am wanting to bind the validation error to my template with NG4, however given the current output of ValidationError[] I have to iterate to find the offender and then pull the message. I then have to bind the message to an object that is bound to the error for that field. I would be nice to get an object output instead of an array that could be bound to.
validationErrors: {
<fieldName>: [{constraint: <constraintName>, message: <actualMessage>}],
<anotherFieldName: [{...},{...}],
...
}
Where in the template I could bind to this result with angular4
md5-823748a89ec2bfbb1b8bb9a80a682703
<input type="email" [(ngModel)]="model.email">
something like this is what I was imagining.
export function validationErrorToObject(ve: ValidationError[]): ValidationObject {
return ve.reduce((p, c:ValidationError) : ValidationObject => {
if(!c.children || !c.children.length) {
p[c.property] = {
value: c.value,
constraints: Object.keys(c.constraints)
.map(key=>{
return capitalize(c.constraints[key])+".\u00a0";
})
}
} else {
p[c.property] = validationErrorToObject(c.children);
}
return p;
}, {} as ValidationObject);
}
export interface ValidationObject {
[key: string]:
{value: string, constraints: string[] } | ValidationObject
}
export function capitalize(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
I support your suggestion. This might be ideal for angular usage.
Just to be clear, so you want a structure like this:
// class definition
class Post {
@IsString()
title: string;
@IsString()
body: string;
@ValidateNested()
author: User
}
// validation result
{
title: [{ constraint: 'isString', message: 'title must be a string.'}],
body: [{ constraint: 'isString', message: 'body must be a string.'}],
author: {
name: [{ constraint: 'isString', message: 'name must be a string.'}],
age: [{ constraint: 'isInit', message: 'age must be an integer.'}],
}
}
Much easier to handle!
Please do not forget that messages need translation and also need to include constraint parameters.
Maybe see #238 for a possible solution.
Most helpful comment
Much easier to handle!
Please do not forget that messages need translation and also need to include constraint parameters.
Maybe see #238 for a possible solution.