Search code examples
angularcustomvalidatorangular-custom-validators

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.

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.


Solution

  • You must handle the special case of moment.format returning the string 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)])
    });