Angular 2(Beta)服务器端验证消息
问题描述:
我正在寻找一种优雅的方法来显示来自服务器端API的验证消息,而不必创建自定义验证程序或对UI中所有可能的消息进行硬编码.
I am looking for an elegant way to display validation messages from a server side API without having to create custom validators or hard coding all possible messages in the UI.
我需要将错误消息添加到特定字段以及整个表单.
I need to add error messages to specific fields as well as to the entire form.
这必须在Angular 2.0.0-beta.3中工作
This must work in Angular 2.0.0-beta.3
答
我向您展示确定的displayErrors函数(按照 JSONAPI 标准处理服务器端验证):
I present you the definitive displayErrors function (Handles server side validations following the JSONAPI Standard):
您将需要Underscore.js
displayErrors(error: ErrorResponse) {
let controls = this.supportRequestForm.controls;
let grouped = _.groupBy(error['errors'], function(e) {
return e['source']['pointer'];
});
_.each(grouped, function(value, key, object) {
let attribute = key.split('/').pop();
let details = _.map(value, function(item) { return item['detail']; });
controls[attribute].setErrors({ remote: details.join(', ') });
});
}