首页 > 解决方案 > 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);
        }
    }
    }
}

它工作正常,但错误消息不起作用

标签: angular-validationhtml5-validation

解决方案


这是您的代码中的错误,您在设置错误之前设置了“return”语句。您需要先设置错误,然后在以下代码中返回 true。

if(age>=18){
    return true;
    _EnterBith.setErrors({DateofBirthValidation:true});
}

上述声明应更新为:-

if(age>=18){
    _EnterBith.setErrors({DateofBirthValidation:true});
    return true;
}

推荐阅读