我们有一个 Angular react 形式,它有一个生日、月份和年份字段。这是代码:
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));
}
}
如何设置生日值最小 01 最大 31?
和月份:最小 01 最大 12?
年份:最少 1950 年,最多 2000 年,例如?
最佳答案
您可以使用 Validators.max和 Validators.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));
}
}
您可以通过访问
errors
手动检查最小/最大验证器的触发。您的 FormGroup 上的属性。console.log(this.SignupForm['controls']['bday'].errors.min);
console.log(this.SignupForm['controls']['bday'].errors.max);
// prints true or false
在您的 component.html 上,您可以包含某种有条件地显示/隐藏的验证消息。
<div class="feedback" *ngIf="SignupForm['controls']['bday'].errors?.min">Minimum date is 1.</div>
关于angular - 如何为 Angular 响应式(Reactive)表单验证设置最小值和最大值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55724416/