9

We have an Angular reactive form which has a birthday, month and years field. Here is the code:

 private buildSignupForm() { this.SignupForm = this.fb.group({ bday: [null, [Validators.required, Validators.maxLength(2)]], bmonth: [null, [Validators.required, Validators.maxLength(2)]], byear: [null, [Validators.required, Validators.maxLength(4), Validators.minLength(4)]], city: [null, [Validators.required, Validators.pattern('[a-zA-Z ]*')]], }); this.SignupForm.setValidators(this.minimumAge(18)); } } 

How can I set birthday value minimum 01 maximum 31? And month: minimum 01 maximum 12? Year: minimum 1950 and max 2000 e.g.?

2 Answers 2

10

You can use Validators.max and Validators.min for that purpose.

 private buildSignupForm() { this.SignupForm = this.fb.group({ bday: [null, [Validators.required, Validators.maxLength(2), Validators.max(31), Validators.min(1)]], bmonth: [null, [Validators.required, Validators.maxLength(2), Validators.max(12), Validators.min(1)]], byear: [null, [Validators.required, Validators.maxLength(4), Validators.minLength(4),Validators.max(2000), Validators.min(1950)]], city: [null, [Validators.required, Validators.pattern('[a-zA-Z ]*')]], }); this.SignupForm.setValidators(this.minimumAge(18)); } } 

You can manually check for the triggering of the min/max validators by accessing the errors property on your FormGroup.

console.log(this.SignupForm['controls']['bday'].errors.min); console.log(this.SignupForm['controls']['bday'].errors.max); // prints true or false 

And on your component.html, you can include some kind of validation message that is shown/hidden conditionally.

<div class="feedback" *ngIf="SignupForm['controls']['bday'].errors?.min">Minimum date is 1.</div> 
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for replying. But will the month accept 01 as well?
@NewTechLover Yes, as long as the input value is interpreted as a number. You can test it out if you want!
Also, I have made some changes on the last 2 blocks of code as we have specify the specific form control in order to access the validator output
1

To change validators after defining the form, you can use the following code:

this.SignupForm.controls['bday'].setValidators([Validators.max(30)]); 

For the months April, June, September, and November, you can add the above code inside a condition statement.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.