【问题标题】:Custom group validator of reactive form causing error TS1068: Unexpected token. A constructor, method, accessor, or property was expected反应形式的自定义组验证器导致错误 TS1068:意外的令牌。需要构造函数、方法、访问器或属性
【发布时间】:2018-01-21 12:01:38
【问题描述】:

所以我有一个带有验证器的反应形式。我创建了自定义验证器来检查密码是否与确认密码匹配。这是它的样子:

this.form = this.formBuilder.group({
        'emailAddress': new FormControl(null, [
            Validators.required,
            Validators.email,
            this.checkEmailAddress.bind(this)
        ]),
        'username': new FormControl(null, [
            Validators.required,
            Validators.maxLength(16),
            this.checkUsername.bind(this)
        ]),
        'passGroup': this.formBuilder.group({
            'password': new FormControl(null, [
                Validators.required
            ]),
            'confirmPassword': new FormControl(null, [
                Validators.required
            ])
        }, {
                validator: checkPassword
            })
    });

这是我的自定义函数:

function checkPassword(group: FormGroup): { [s: string]: boolean } {
    if (group.value.password !== group.value.confirmPassword) {
        return { 'passwordMismatch': true };
    }
    return null;
}

经过一番谷歌搜索,我发现我不应该使用 function 这个词。然而,这是令人困惑的部分。

如果我重新保存(没有任何实际更改),编译器将重新编译并且它会成功。

如果我删除函数这个词,编译器也会成功,但是我的表单的验证器会被破坏。

我也试过
validator: this.checkPasswordvalidator: this.checkPassword.bind(this) 删除功能词后,但它给了我很多错误。

【问题讨论】:

    标签: angular validation typescript angular5


    【解决方案1】:

    基于Angular2 validator which relies on multiple form fields你可以在component.ts中放入validators函数,称为this.functionName

        this.form = this.formBuilder.group({
           ...,
          'passGroup': this.formBuilder.group({
            'password': new FormControl(null, [
              Validators.required
            ]),
            'confirmPassword': new FormControl(null, [
              Validators.required
            ])
          }, {
              validator: this.checkPassword('password', 'confirmPassword')
            })
        });
    
    checkPassword(passwordKey: string, confirmPasswordKey: string) {
        return (group: FormGroup): { [key: string]: any }| null => {
          let password = group.get(passwordKey);
          let confirmPassword = group.get(confirmPasswordKey);
          if (password.value == confirmPassword.value)
            return null;
          return {
            mismatchedPasswords: true
          };
        }
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-01
      • 2016-09-12
      • 2017-03-22
      • 2016-03-30
      • 2018-07-07
      • 1970-01-01
      相关资源
      最近更新 更多