Learner
Learner

Reputation: 21393

Using HTML5 pattern with Angular

I have a date element in my component HTML file:

<input type="text" name="travelDate" 
    placeholder="Date YYYY-MM-DD" name="travelDate" class="form-control" 
    pattern="\d{4}/\d{1,2}/\d{1,2}" formControlName="travelDate">

<button class="btn btn-info" type="submit">Search</button>

It is just a text field that allows the user to enter date value, now I want to restrict that to format YYYY-MM-DD so I am using the above pattern.

Now when I enter some random text abc and then click the submit button I am not getting any alert message saying the travelDate field is not valid.

How to use pattern in Angular component HTML file?

Upvotes: 1

Views: 120

Answers (1)

Ghoul Ahmed
Ghoul Ahmed

Reputation: 4806

use Validator.pattern in Formcontrol like this:

     myForm: FormGroup;

    this.myForm = this.fb.group({
      'travelDate': ['', Validators.pattern(/\d{4}/\d{1,2}/\d{1,2}/)]
    }) 

to get alert after submitting:

submit(){

    if(this.myForm.get('travelDate').invalid){
       alert('invalid date')
    }

}

Upvotes: 1

Related Questions