【问题标题】:Angular Custom Validation error meassage not workingAngular 自定义验证错误消息不起作用
【发布时间】:2021-02-02 23:27:13
【问题描述】:

这是我的自定义验证工作,但它的错误消息不起作用

 <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-validation html5-validation


【解决方案1】:

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

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

上述语句应更新为:-

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-28
    • 1970-01-01
    • 2020-03-19
    • 1970-01-01
    • 2018-08-09
    相关资源
    最近更新 更多