我有一个表格,其中有五个字段
street,buildingNo,city,state,zip
我必须对onsubmit做一些验证,这就是我这样做的方式:
searchByCriteria(){
this.gridOptions.rowData = [];
this.isValid = true;
this.queryParam = this.searchForm.value;
this.errors = [];
if ((this.errors.length == 0) && (this.queryParam.zip && !isNumeric(this.queryParam.zip))) {
this.isAnyCriteriaEntered = false;
this.isValid = false;
this.errors.push("Zip should be numeric");
this.hideEnterCriteriaLabel = true;
}
if ((this.errors.length == 0) && ((this.queryParam.city
&& this.queryParam.state) || this.queryParam.buildingNo ||
(this.queryParam.zip && isNumeric(this.queryParam.zip)))) {
this.isValid = true;
this.isAnyCriteriaEntered = true;
this.hideEnterCriteriaLabel = true;
}
if ((this.errors.length == 0) && (((this.queryParam.state && !this.queryParam.city)
|| (!this.queryParam.state && this.queryParam.city))
&& !this.queryParam.buildingNo && !this.queryParam.zip)) {
this.errors.push("Please enter a value for State and City or Postal Code or Building Number");
this.isValid = false;
this.isAnyCriteriaEntered = true;
this.hideEnterCriteriaLabel = true;
}
if (!this.queryParam.street && !this.queryParam.city
&& !this.queryParam.state && !this.queryParam.zip
&& !this.queryParam.buildingNo) {
this.isAnyCriteriaEntered = false;
this.isValid = false;
this.hideEnterCriteriaLabel = false;
}
if (this.queryParam.street && !this.queryParam.city
&& !this.queryParam.state && !this.queryParam.zip
&& !this.queryParam.buildingNo) {
this.errors.push("Please enter a value for State and City or Postal Code or Building Number");
this.isAnyCriteriaEntered = true;
this.isValid = false;
this.hideEnterCriteriaLabel = true;
}
if (this.isValid) {
this.searchStatus.beginLoading();
this.hideEnterCriteriaLabel = true;
this.propertyService.getAddresses(this.queryParam)
.subscribe(
addresses => {
this.addresses = addresses;
if (addresses.length > 0) {
this.searchSuccess();
} else {
this.errors.push("Zero addresses meet this selection");
this.searchFailure();
}
},
error => this.searchStatus.markFailure());
}
}
searchByCriteria()
在onsubmit of form上被调用。
而不是使用errors数组,然后在html代码中迭代该数组并显示错误 在div中是否有更好的方法来处理angular4中的onsubmit上的验证并显示错误?
答案 0 :(得分:0)
是否可以升级到Angular 5?
Angular 5增加了在更改时自动执行验证的功能(如在Angular 2到4中),模糊或提交时。
<form [ngFormOptions]="{ updateOn: 'submit' }">
在此处查找更多信息:https://medium.com/codingthesmartway-com-blog/angular-5-forms-update-9587c3735cd3