angular-validation - Angular 自定义验证错误消息不起作用
问题描述
这里我的自定义验证工作但它的错误消息不起作用
<input type="date" formControlName="Appli_DOB" [ngClass]="{ 'is-invalid': f.Appli_DOB.touched && f.Appli_DOB.errors }">
<span *ngIf="f.Appli_DOB.hasError.DateofBirthValidation">Age Should be Greater Than 18 Years</span>
角
ngOnInit() {
this._MyregisterForm = this.formBuilder.group({
Appli_DOB:['',Validators.required],
validator: DateofBirthValidation('Appli_DOB')
});
客户错误验证
import { FormGroup } from '@angular/forms';
export function DateofBirthValidation(EnteredBirth:any){
return (group:FormGroup)=>{
let _EnterBith=group.controls[EnteredBirth];
if(_EnterBith.value!=""){
let timeDiff = Math.abs(Date.now() -new Date(_EnterBith.value).getTime());
var age = Math.floor((timeDiff / (1000 * 3600 * 24))/365);
console.log(age)
if(age>=18){
return true;
_EnterBith.setErrors({DateofBirthValidation:true});
}
else{
_EnterBith.setErrors({DateofBirthValidation:false});
// _EnterBith.setErrors(null);
}
}
}
}
它工作正常,但错误消息不起作用
解决方案
这是您的代码中的错误,您在设置错误之前设置了“return”语句。您需要先设置错误,然后在以下代码中返回 true。
if(age>=18){
return true;
_EnterBith.setErrors({DateofBirthValidation:true});
}
上述声明应更新为:-
if(age>=18){
_EnterBith.setErrors({DateofBirthValidation:true});
return true;
}
推荐阅读
- python-3.x - python pop() 用于具有转移值的列表
- browser - 在非默认浏览器上启动 pgAdmin v4
- post - POST 请求在 Jmeter 重放期间显示为 GET 请求
- android - 颤振120fps问题
- localization - Wikidata SPARQL:如何包含分组属性的标签
- java - 了解远程查找的 EJB 属性
- html - React Bootstrap 下拉菜单在数据网格中部分可见
- javascript - 创建一个在变量未定义时解析的 Promise
- r - 编织降价时如何解决此错误
- python - 如何使用python中另一列的值创建一个新列