如何设置 Angular 反应式表单验证的最小值和最大值?

New*_*ver 8 typescript angular angular6

我们有一个 Angular 响应式表单,其中包含生日、月份和年份字段。这是代码:

 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));
  }
}
Run Code Online (Sandbox Code Playgroud)

如何设置生日值最小值 01 最大值 31?月份:最小 01 最大 12?年份:最小 1950 年,最大 2000 年,例如?

wen*_*jun 9

您可以使用Validators.maxValidators.min来实现此目的。

 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));
  }
}
Run Code Online (Sandbox Code Playgroud)

errors您可以通过访问FormGroup 上的属性来手动检查最小/最大验证器的触发。

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

在你的 component.html 上,你可以包含某种有条件地显示/隐藏的验证消息。

<div class="feedback" *ngIf="SignupForm['controls']['bday'].errors?.min">Minimum date is 1.</div>
Run Code Online (Sandbox Code Playgroud)