1

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?

1 Answer 1

1

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')
    }

}
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.