在此演示中,我为自定义验证器创建了一个示例表单, 在这里,我有From date和TO date以及time and To time, 工作正常: 迄今为止,验证工作正常,并显示错误消息。
问题: 当选择相同的日期,例如)2018年7月21日与该日期相同,并且在To da e和In 中,从Time为4:00 AM和To Time为3:00 AM时,条件得到满足,但未显示错误消息。实现过程中发生了错误,有人可以帮我解决赞赏的情况
在html中,我给出了验证消息,但未显示。
To Time:
<input type="time" formControlName="ToTime">
<mat-error *ngIf="DaterForm.get('ToTime').hasError('InValidToTime')">FromTime Should be less than ToTime if choose a same date</mat-error>
在组件中:
DaterForm : FormGroup;
constructor(private fb:FormBuilder){
}
ngOnInit(){
this.DaterForm = this.fb.group(
{
FromDate:['',[AppCustomDirective.fromDateValidator]], // validation working fine
FromTime:[''],
ToDate:['',[AppCustomDirective.ToDateValidator]],// validation working fine
ToTime:['']
},{validator:[AppCustomDirective.timeValidator] // validation not working
}
自定义验证:
import { AbstractControl, FormControl, FormGroup, ValidatorFn, Validators } from '@angular/forms';
export class AppCustomDirective extends Validators{
static fromDateValidator(fdValue: FormControl) {
const date = fdValue.value;
console.log('x');
if (date ===null || date==='') return { requiredFromDate: true };
}
static ToDateValidator(todValue: FormControl) {
const date = todValue.value;
if (date ===null || date==='') return { requiredToDate: true };
}
static timeValidator(formGroupValues: FormGroup): any {
debugger;
console.log(formGroupValues);
const FromDate = formGroupValues.get('FromDate').value;
const ToDate = formGroupValues.get('ToDate').value;
const FromTime = formGroupValues.get('FromTime').value;
const ToTime = formGroupValues.get('ToTime').value;
if (FromDate.toString() === ToDate.toString()) {
let fromTime = [];
let toTime = [];
fromTime = FromTime.split(':');
toTime = ToTime.split(':');
if (parseInt(fromTime[0]) > parseInt(toTime[0])){
alert("condition satisfied not return any error message");
return { InValidToTime: true };
}
else if (
parseInt(fromTime[0]) === parseInt(toTime[0]) &&
parseInt(fromTime[1]) > parseInt(toTime[1])
){ alert("condition satisfied not return any error message")
return { InValidToTime: true };
}
}
}
}
答案 0 :(得分:1)
这是因为您希望在特定输入中出现错误而在表单上设置错误。
更改为<mat-error *ngIf="DaterForm.hasError('InValidToTime')">
可以解决此问题。
仅供参考,mat-error
不能与<input matInput/>
一起使用
https://stackblitz.com/edit/angular-customvalidator-1fu5vx?file=app/datepicker-overview-example.html