【发布时间】:2018-06-29 16:26:15
【问题描述】:
我查看了多个问题,所有答案都用于在表单组上设置验证器。我知道如何使用如下所示的表单生成器。
this.userForm = this.fb.group({
id: '',
firstName: ['', [Validators.required]],
lastName: ['', [Validators.required]],
email: ['', [Validators.required]],
phoneNumber: ['', [Validators.required]],
jobTitle: ['', [Validators.required]],
team: ['', [Validators.required]],
passwords: this.fb.group({
password: '',
confirmPassword: ''
},{
validator: Validators.compose([PasswordValidators.MatchPassword, PasswordValidators.PasswordRequirements])
}),
userValues: this.fb.array([])
});
现在我的组件有两种模式,添加和编辑。如果添加了模式,则密码控件应使用所需的验证器。我检查模式,如果它不在编辑模式下,我想更新密码表单组上的验证器以包含所需的验证器。我已经在 ngInit 事件中尝试过,如下所示。
// if not edit mode then the password fields are required, so we overwrite the default validators.
if(!this.isEditMode)
{
console.log("user form mode: " + this.isEditMode)
const passwordForm = <FormGroup>this.userForm.controls['passwords'];
// try to set the validators on the form group as a whole.
passwordForm.setValidators([PasswordValidators.MatchPassword, PasswordValidators.PasswordRequirements, Validators.required]);
// try to set the password on the individual control.
passwordForm.controls['password'].setValidators([PasswordValidators.MatchPassword, PasswordValidators.PasswordRequirements, Validators.required]);
}
现在我第一次尝试更新表单组中的验证器一段时间没有任何区别。我们更新单个表单控件的第二次尝试导致我的验证器抛出异常。那么我是否可以将其应用于表单组而无需更改验证器的工作方式。验证器如下所示。
import { AbstractControl, ValidatorFn } from '@angular/forms';
export class PasswordValidators {
static MatchPassword(AC: AbstractControl){
let password = AC.get('password').value; // to get value in input tag
let confirmPassword = AC.get('confirmPassword').value; // to get value in input tag
if(!password || password == "")
{
return null;
}
if(password != confirmPassword) {
AC.get('confirmPassword').setErrors( {MatchPassword: true} );
} else {
return null;
}
}
// Ensures the password meets the minimum standard. Password should be at least 8 char, contain one numeric, one character, and one special character.
static PasswordRequirements(AC: AbstractControl) {
let password = AC.get('password').value;
if(!password || password == "")
{
return null;
}
if(password != password.match("^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{8,}$")) {
AC.get('password').setErrors({PasswordRequirements: true})
} else {
return null;
}
}
}
任何关于我如何实现这一目标的建议都会很棒。干杯。
【问题讨论】:
-
您正在混合验证整个组的验证器(MatchPassword、PasswordRequirements),因此需要在组上设置,以及验证单个控件的验证器(Validators.required,它检查输入值不是 null 或空),因此必须在控件上设置。还不清楚为什么您没有从一开始就设置正确的验证器:您在创建表单组时已经知道组件的模式,不是吗?
-
是的,我确实知道模式,但为了减少代码量,我不想有两个单独的表单定义。尽管现在听起来更容易使用该选项。感谢您对验证器的解释,过去几周我只使用 Angular,所以我还有很多东西要学。
标签: angular validation typescript angular-components angular-reactive-forms