simeonshopov

Angular datepicker event handler

Nov 6th, 2025
714
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. onDateInputChange(event: any): void {
  2.     const raw: any = (event && (event.currentTarget?.value
  3.       ?? event.target?.value
  4.       ?? (typeof event === 'string' ? event : undefined)))
  5.       ?? '';
  6.  
  7.     const val: string = String(raw).trim();
  8.  
  9.     const ctrl: AbstractControl = this.fields && this.fields['proxy_date'];
  10.     const applyInvalid: () => void = (): void => {
  11.       if (!ctrl) { return; }
  12.       ctrl.setValue(null, { emitEvent: false });
  13.       ctrl.updateValueAndValidity({ onlySelf: true, emitEvent: false });
  14.       const errs: { [key: string]: any } = { ...(ctrl.errors || {}) };
  15.       errs['invalidDate'] = true;
  16.       ctrl.setErrors(errs);
  17.       ctrl.markAsTouched();
  18.     }
  19.  
  20.     const removeInvalidFlagIfPresent: () => void = (): void => {
  21.       if (!ctrl) { return; }
  22.       const errs = { ...(ctrl.errors || {}) };
  23.       if (errs['invalidDate']) { delete errs['invalidDate']; }
  24.       ctrl.setErrors(Object.keys(errs).length ? errs : null);
  25.     };
  26.  
  27.     if (!val) { applyInvalid(); return; }
  28.     const match: RegExpMatchArray|null = val.match(/^\s*(\d{1,2})\s*[.\-\/]\s*(\d{1,2})\s*[.\-\/]\s*(\d{4})\s*$/);
  29.     if (!match) { applyInvalid(); return; }
  30.  
  31.     const day: number = parseInt(match[1], 10);
  32.     const month: number = parseInt(match[2], 10);
  33.     const year: number = parseInt(match[3], 10);
  34.  
  35.     if (!Number.isFinite(day) || !Number.isFinite(month) || !Number.isFinite(year)) {
  36.       applyInvalid(); return;
  37.     }
  38.  
  39.     if (month < 1 || month > 12) {applyInvalid(); return;}
  40.  
  41.     const daysInMonth: number = new Date(year, month, 0).getDate();
  42.     if (day < 1 || day > daysInMonth) {applyInvalid(); return;}
  43.  
  44.     const parsed = new Date(year, month - 1, day);
  45.     if (parsed.getFullYear() !== year
  46.       || parsed.getMonth() !== month - 1
  47.       || parsed.getDate() !== day
  48.       || isNaN(parsed.getTime())
  49.     ) {
  50.       applyInvalid(); return;
  51.     }
  52.  
  53.     if (ctrl) {
  54.       ctrl.setValue(parsed, { emitEvent: false });
  55.       ctrl.updateValueAndValidity({ onlySelf: true, emitEvent: false });
  56.       removeInvalidFlagIfPresent();
  57.     }
  58.   }
Advertisement
Add Comment
Please, Sign In to add comment