Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set minimum and maximum values for Angular reactive form validation?

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

like image 459
NewTech Lover Avatar asked May 21 '26 02:05

NewTech Lover


2 Answers

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>
like image 155
wentjun Avatar answered May 22 '26 16:05

wentjun


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.

like image 44
Mustafa Bazghandi Avatar answered May 22 '26 17:05

Mustafa Bazghandi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!