【发布时间】:2023-09-23 02:29:01
【问题描述】:
我有一个表单,其中有五个字段
街道、建筑物编号、城市、州、邮编
我必须对 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 验证并显示错误?
【问题讨论】:
-
一些作者建议使用变量,例如“已提交”,在 onsumbmit 中变为真,并在出现错误且此变量等于真时显示错误
标签: angular angular4-forms angular-validation