0

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" class="form-control form-cntrl" 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" class="text-danger">Start Date is required</small>
                <small *ngIf="startDt.errors.pattern" class="text-danger">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!

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.