代码之家  ›  专栏  ›  技术社区  ›  Tony_89

在formgroup上设置验证器

  •  4
  • Tony_89  · 技术社区  · 8 年前

    我看了多个问题,所有的答案都是为了在表单组上设置验证器。我知道如何使用如下所示的表单生成器进行此操作。

     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([])
    });
    

    现在我的组件有两种模式,添加和编辑。如果模式为add,则密码控件应使用所需的验证器。我检查模式,如果它不在编辑模式,我想更新密码表单组上的验证器,以包含所需的验证器。我已经在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;
            }
    
        }
    }
    

    任何关于我如何实现这一目标的建议都将非常好。干杯

    1 回复  |  直到 8 年前
        1
  •  4
  •   Tony_89    8 年前

    为了解决这个问题,因为我知道我的形式处于什么状态,我实际上有两个不同的形式定义 JB Nizet 在他的评论中提到。

    它看起来不像是最干净的解决方案,但对于这个用例,它是有效的。

    if(!this.isEditMode) {
      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:  ['', Validators.required],
          confirmPassword:  ['', Validators.required]
        },{
          validator: Validators.compose([PasswordValidators.MatchPassword, PasswordValidators.PasswordRequirements])
        }),
        userValues: this.fb.array([]),
        roles: []
      });
    } else { 
      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([]),
        roles: []
      });
    }
    
    推荐文章