没有内置的验证器采用额外的参数来描述错误。但是为此,您可以编写自己的。
让我们以内置minLength
验证器为例。我们添加了第二个名为desc的参数,它将保存自定义错误消息。
class CustomValidators {
static minLengthWithDescription(minLength: number, desc: string): Function {
return (control: modelModule.Control): {[key: string]: any} => {
return v.length < minLength ?
{"minlength": {
"requiredLength": minLength,
"actualLength": v.length,
"desc": desc // Here we pass our custom error message
}
} : null;
};
}
}
如你所见,我们几乎没有碰过原来的那个。现在就像检查我们的视图一样简单,如果错误消息存在
<form [ngFormModel]="myForm">
<p>
Year: <input ngControl="year">
// We use the Elvis operator to check if the error exists or not
// if exists it will print the error message
{{myForm.controls.year.getError('minlength')?.desc}}
</p>
</form>
最后我们设置我们想要显示的错误信息
export class App {
year: Control = new Control('',
CustomValidators.minLengthWithDescription(4, 'Wrong ammount of numbers'));
}
这是一个带有示例工作的plnkr 。