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.?
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>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With