0

I have to check given value is matching with specific date format like "MM/dd/YYYY"

Ts file

onValChange(event: Date) {
    const datePipe = new DatePipe('en-US');
    const val = datePipe.transform(event, 'MM/dd/yyyy');
    this.writeValue(moment(event));
  }

Html file

<input class="form-control form-control-sm requiredV" [(ngModel)]="dateValue"
     placeholder="mm/dd/yyyy" name="dateField" id="dateField" ngbDatepicker
     #dateFieldngb="ngbDatepicker" [required]="isRequired"
     [ngClass]="{'isUntouched':formName.submitted}" (ngModelChange)="onValChange($event)"
     (keypress)="allow_only_numbers($event)" (click)="dateFieldngb.toggle()" />

Can you please tell me how to check entered value is matching with this specific format or not

Iñigo
  • 1,877
  • 7
  • 25
  • 55
Olive
  • 149
  • 1
  • 4
  • 13

3 Answers3

1

I usually use an external library to control dates.

https://momentjs.com

This library provides a function valid. You can implement this function like this

moment(date, 'MM/DD/YYYY').isValid()
0

You can filter your data using date pipe, please check given reference.

Angular Date Pipe

Piyush Jain
  • 1,895
  • 3
  • 19
  • 40
0

You can do this either by using a library or writing a custom function

  1. Library - moment-js

    Example:

moment("2010 13",           "YYYY MM").isValid();     // false (not a real month)
moment("2010 11 31",        "YYYY MM DD").isValid();  // false (not a real day)
moment("2010 2 29",         "YYYY MM DD").isValid();  // false (not a leap year)
moment("2010 notamonth 29", "YYYY MMM DD").isValid(); // false (not a real month name)

Referred from this thread.


  1. Custom function using Regular expression
var date_regex = /^(0[1-9]|1[0-2])\/(0[1-9]|1\d|2\d|3[01])\/(19|20)\d{2}$/ ;

if(!(date_regex.test(testDate))){
  return false;
}

Referred from this thread

saintlyzero
  • 1,632
  • 2
  • 18
  • 26