Home > other >  Angular SetValidators Pattern Valid Date RegEx error
Angular SetValidators Pattern Valid Date RegEx error

Time:02-05

I have been reading a few posts here on validating a date formcontrol with regexpression but most of them are using custom date validation code. I am trying to get the reactive form setValidators approach with the date regexpression inside the pattern method. I found a few date regexpression but I am getting an error where the validation error is trigged even for valid MM/DD/YYYY format.

For the reg expression I tried the following strings

datePattern1: string = '^\d{2}\/\d{2}\/\d{4}$';

datePattern1: string = '^(0?[1-9]|[12][0-9]|3[01])[/-](0?[1-9]|1[012])[/-]\\d{4}$';

For the Reactive Form date control is the TS code

 startDate?.setValidators([Validators.required, 
                Validators.pattern(this.datePattern1)];

In the HTML code

<input type="date"  formControlName="startDt"  aria-label="Start Date"
              [ngClass]="{'has-error': (startDt.invalid && startDt.touched)}" >
              <span *ngIf="startDt.invalid && startDt.touched">
                <br/>
                <small *ngIf="startDt.errors.required" >Start Date is required</small>
                <small *ngIf="startDt.errors.pattern" >Start Date Format MM/DD/YYYY is invalid</small>
              </span>

The required validator is working fine. But the Date Format is always triggering. I tried 3 regex string I found here from a few posts, but I can't get it to work.

Any help would be great! Thanks!

CodePudding user response:

I've had the same issue in the past. In my experience, you're better of defining the patterns directly as RegExp with the format /regexp/. Because if you use a string, you have to escape also the backslashes for it to work and it's easy to forget.

As an example your first pattern can be either:

datePattern1: RegExp = /^\d{2}\/\d{2}\/\d{4}$/

Or using a string it should be:

datePattern1: string = '^\\d{2}\\/\\d{2}\\/\\d{4}$'

cheers

  •  Tags:  
  • Related