简体   繁体   English

如何使用自定义验证来验证 angular 中的无效日期

[英]How can validate invalidate date in angular by using custom validation

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.我正在使用自定义验证器创建日期验证器,但是当我打印错误时它显示 null。我正在尝试输入它接受的 2222-22-22 之类的内部日期,在这里我使用自定义验证器来限制此类无效日期。

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也在 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.每当我插入像 1111-11-11、2222-22-22 或 4444-44-44 这样的日期时,它应该给出一个错误的无效日期。 Or date should be greater than 1900. But as result it doesn't give any error, how can I implement this.或者日期应该大于 1900。但是结果它没有给出任何错误,我该如何实现它。

You must handle the special case of moment.format returning the string Invalid date您必须处理moment.format返回字符串Invalid date的特殊情况

export function minYearValidator(year: number) {
   return (control: AbstractControl) => {
     const validationString = moment(control.value).format("YYYY");
     if(validationString === "Invalid date" || Number(validationString) < year)
      return {ValidateDate: {value: true}}
     return null
   }
}

for your form:对于您的表格:

import {minYearValidator} from './path/to/function/file';

this.myForm = new FormGroup({
date: new FormControl('',[Validators.required, minYearValidator(1900)])
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM