如何使用自定义验证如何验证Angular中的无效日期
我正在通过使用自定义验证器创建日期验证器,但是当我打印错误时,它显示为null。 我正在尝试像2222-22-22一样输入间日期,在这里我使用自定义验证器来限制此类无效日期。
我的代码是..
myFrom: FormGroup;
cosntructor(private myService:ValidatorsService){
this.myForm = new FormGroup({
date: new FormControl('',[Validators.required,this.myService.ValidateDate])
});
}
我的验证服务
ValidateDate=(control: AbstractControl): ValidationErrors | null => moment(control.value).format('YYYY') < '1900'?{ValidateDate:{value:true}}:null
也有HTML。
<form [formGroup]="myForm">
<mat-from-field [formGroup]="myForm">
<mat-label>Enter Date</mat-label>
<input matInput type="datetime-local" [step]="1" formControlName="date" required >
<mat-error *ngIf="myForm.controls.date.hasError('required')">
Please Enter Date
</mat-error>
<mat-error *ngIf="myForm.controls.date.errors?.ValidateDate">
Invalid Date
</mat-error>{{myForm.get('date')?.errors | json}}
</mat-from-field>
</form>
当我插入像1111-11-11、2222-22-22或4444-44-44时, 它应该给出一个错误日期。或日期应大于1900。 但是由于它没有任何错误,我该如何实现。
I am creating a date validator by using custom validator but when I print the error it shows null.
I am trying to enter inter date like 2222-22-22 it accept, here I have use custom validator to restrict such invalidate date.
my code is..
myFrom: FormGroup;
cosntructor(private myService:ValidatorsService){
this.myForm = new FormGroup({
date: new FormControl('',[Validators.required,this.myService.ValidateDate])
});
}
and my validating service have
ValidateDate=(control: AbstractControl): ValidationErrors | null => moment(control.value).format('YYYY') < '1900'?{ValidateDate:{value:true}}:null
also in html
<form [formGroup]="myForm">
<mat-from-field [formGroup]="myForm">
<mat-label>Enter Date</mat-label>
<input matInput type="datetime-local" [step]="1" formControlName="date" required >
<mat-error *ngIf="myForm.controls.date.hasError('required')">
Please Enter Date
</mat-error>
<mat-error *ngIf="myForm.controls.date.errors?.ValidateDate">
Invalid Date
</mat-error>{{myForm.get('date')?.errors | json}}
</mat-from-field>
</form>
Whenever I insert date like 1111-11-11, 2222-22-22 or 4444-44-44
it should give an error invalid date. Or date should be greater than 1900.
But as result it doesn't give any error, how can I implement this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您必须处理
moment.format
返回字符串无效日期
的特殊情况:
You must handle the special case of
moment.format
returning the stringInvalid date
for your form: