angular2 表单验证器中的验证描述
Validation description in angular2 forms validators
通过angular2看api控件class我明白了
minLength(minLength: number) : Function
我明白函数的作用。
我想知道当验证失败时出现问题的描述是否不能放在函数中。
例如,我想知道函数是否可以
minLength(minLength: number, description: string) : Function
其中描述描述了如下所示的错误原因
Control firstCtrl = new Control( '', Validators.minLength(2, description: 'Minium of two characters required) );
我没能在 API 中找到任何类似的验证器。如果可以分享 link/explanation,我会很高兴。
期待看到您的反馈。
没有builtin Validators需要一个额外的参数来描述错误。但是你可以自己写。
让我们以内置 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 的示例。
通过angular2看api控件class我明白了
minLength(minLength: number) : Function
我明白函数的作用。
我想知道当验证失败时出现问题的描述是否不能放在函数中。
例如,我想知道函数是否可以
minLength(minLength: number, description: string) : Function
其中描述描述了如下所示的错误原因
Control firstCtrl = new Control( '', Validators.minLength(2, description: 'Minium of two characters required) );
我没能在 API 中找到任何类似的验证器。如果可以分享 link/explanation,我会很高兴。
期待看到您的反馈。
没有builtin Validators需要一个额外的参数来描述错误。但是你可以自己写。
让我们以内置 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 的示例。