我有一个表单,其中有五个字段
街道、buildingNo、城市、州、邮政编码
我必须在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()。
与使用错误数组然后在html代码中迭代数组并在div中显示错误相比,有没有更好方法来处理angular4中的onsubmit的验证并显示错误?
发布于 2017-12-14 15:50:50
有可能升级到Angular 5吗?
Angular 5添加了在更改(如在Angular 2到4中)、模糊或提交时自动执行验证的能力。
<form [ngFormOptions]="{ updateOn: 'submit' }">更多信息请点击这里:https://medium.com/codingthesmartway-com-blog/angular-5-forms-update-9587c3735cd3
https://stackoverflow.com/questions/47807673
复制相似问题