Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Reactive Forms validation date year four digits

I use Angular Reactive Forms and I want valid the format of my date in priority (before the two existing validators). My valid format is dd/MM/YYYY (not dd/MM/YY). I use a bootstrap v4 date picker.

My form:

this.myForm = this.fb.group({
  'day': ['', [Validators.required, minDateValidator(this.todayMoment.toDate()), businessDayValidator()]]
});

My validators:

export function minDateValidator(minDate: Date): ValidatorFn {
  return (control: AbstractControl): {[key: string]: any} | null => {
    const invalid = control.value < minDate.setHours(0, 0, 0);
    return invalid ? {'minDate': {value: control.value}} : null;
  };
}

export function businessDayValidator(): ValidatorFn {
  return (control: AbstractControl): {[key: string]: any} | null => {
    const invalid = !DateUtilsService.isBusinessDay(moment(control.value));
    return invalid ? {'businessDay': {value: control.value}} : null;
  };
}

I try add this Validators.pattern('(2|1)[0-9]{3}-[0-9]{2}-[2-9]{2}.*')

online regex exec is OK but not in Angular (print this error):

{ "pattern": { "requiredPattern": "^(2|1)[0-9]{3}-[0-9]{2}-[2-9]{2}.*$", "actualValue": "2019-04-15T10:00:00.000Z" } }
like image 789
Stéphane GRILLON Avatar asked Sep 11 '25 21:09

Stéphane GRILLON


1 Answers

the problem in bootstrap datepicker is "the value is a date not a string".

this.myForm = this.fb.group({
  'day': ['', [Validators.required, formatValidator(), minDateValidator(this.todayMoment.toDate()), businessDayValidator()]]
});

export function formatValidator(): ValidatorFn {
  return (control: AbstractControl): {[key: string]: any} | null => {
    const dateRegEx = new RegExp('^(2|1){1}[0-9]{3}.[0-9]{2}.[0-9]{2}.*$');
    const dateInput = control.value as Date;
    const match = dateInput.toISOString && dateRegEx.test(dateInput.toISOString());
    return  match ? null : {'formatValidator': {value: control.value} };
  };
}
like image 164
Stéphane GRILLON Avatar answered Sep 13 '25 12:09

Stéphane GRILLON