【问题标题】:angular 2 group validation角度 2 组验证
【发布时间】:2017-02-24 07:15:14
【问题描述】:

给定简单的注册表:

this.registerForm = this.formBuilder.group({
    email:['', Validators.compose([
    Validators.required,
    Validators.pattern('.+@.+\..+'),
    ]), this.validators.isTaken],
    matchingPassword: this.formBuilder.group({
    password: ['', Validators.compose([
            Validators.required,
            Validators.maxLength(30),
            Validators.minLength(8)
        ])],
    passwordConfirmation: ['', Validators.compose([
            Validators.required,
        ])]
    }, {validator: this.validators.match})
})

我正在尝试验证密码确认匹配,因此我将匹配验证器应用于表单组。但是现在我面临的情况是字段本身显示为有效(绿色边框,因为它的所有验证器都通过)但组验证器不是,我需要将它们显示为红色。

那么我应该手动将 ng-valid 更改为 ng-invalid 还是有一些技巧可以更好地解决这个问题?

【问题讨论】:

  • 对于您的特定示例,我会将自定义matchingPasswordValidator 放在passwordConfirmation 字段中,因为该字段的内容仅在匹配密码时才有效。对于更通用的组验证器,我只会为整个组提供一般错误消息。
  • @HarryNinh,这种方法的问题在于,如果我将匹配验证器放入passwordConfirmation,它只会在此字段更改时触发。我的意思是,如果您更改 password 字段以使其与 passwordConfirmation 匹配,最后一个仍将标记为无效,因为未在该字段上运行验证。
  • 啊,你可以订阅passwordvalueChanges事件调用passwordConfirmationControl.updateValueandValidity()函数。
  • SET,找到解决方案了吗?

标签: angular angular2-forms


【解决方案1】:

我刚刚在这里[1]回答了这个问题。

基本上,Angular 不会假设您要使组的所有字段无效,因为该组无效。您可以在模板本身中补充该信息。

我没有您的模板,但我或多或少可以假设您可以通过以下方式将控件更改为无效:

<input [ngClass]="{'ng-invalid': registerForm.get('matchingPassword').hasError('nomatch')}" type="text" placeholder="Password" formControlName="password">

<input [ngClass]="{'ng-invalid': registerForm.get('matchingPassword').hasError('nomatch')}" type="text" placeholder="Confirm password" formControlName="passwordConfirmation">

您可能需要调整自定义验证器返回的占位符和错误名称ma​​tch

[1]FormControl`s of nested FormGroup are ng-valid although FromGroup is ng-invalid

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-14
    相关资源
    最近更新 更多