Angular2反应式表单根据验证失败条件显示错误消息

Angular2反应式表单根据验证失败条件显示错误消息,angular,validation,angular-reactive-forms,Angular,Validation,Angular Reactive Forms,我想提到的是,我使用单独的泛型组件来显示错误,所以我没有将它们直接放在html中以避免重复,所以我不能直接在模板中链接和硬编码条件 我已应用此字段和两个验证: this.username = new FormControl('', [ Validators.minLength(5), Validators.required ]); 如何显示每个验证的验证错误消息?假设在提交时,如果字段中没有任何内容,我希望显示这两个错误: “最小长度为5” “字段为必填项” 然后,如果你把东西放进去,它只会

我想提到的是,我使用单独的泛型组件来显示错误,所以我没有将它们直接放在html中以避免重复,所以我不能直接在模板中链接和硬编码条件

我已应用此字段和两个验证:

this.username = new FormControl('', [ Validators.minLength(5), Validators.required ]); 
如何显示每个验证的验证错误消息?假设在提交时,如果字段中没有任何内容,我希望显示这两个错误:
“最小长度为5”
“字段为必填项”

然后,如果你把东西放进去,它只会显示:
“最小长度为5”

这是一个示例,但我的实际示例是比较两个电子邮件字段,如果它们相同,那么如果电子邮件不正确,则应显示:
“电子邮件不正确”
“电子邮件与第一个电子邮件字段不同”

因此,如果电子邮件是正确的,并且电子邮件不相同,则只应显示:
“电子邮件与第一个电子邮件字段不同”

如果没有通过,我的验证可以工作,但是我不确定如何分别显示一个验证通过了,另一个验证没有通过,因为我必须正确地附加失败的真正原因,而不是为这两个原因添加一些通用的原因

完整示例:

用于错误显示的组件:

import { Component, OnInit, Input } from '@angular/core';

@Component({
  selector: 'app-field-error-display',
  templateUrl: './field.error.display.component.html',
  styleUrls: ['./field.error.display.component.css']
})
export class FieldErrorDisplayComponent
{
    @Input() errorMsg: string;
    @Input() displayError: boolean;
}
组件html:

<div *ngIf="displayError" >
  <small>{{errorMsg}}</small>
</div>
自定义匹配其他验证程序:

import { FormControl } from '@angular/forms';

export class MatchOtherValidator {
    static Validate(otherControlName: string) {

        let thisControl: FormControl;
        let otherControl: FormControl;

        return function matchOtherValidate(control: FormControl) {

            if (!control.parent) {
                return null;
            }

            // Initializing the validator.
            if (!thisControl) {
                thisControl = control;
                otherControl = control.parent.get(otherControlName) as FormControl;
                if (!otherControl) {
                    throw new Error('matchOtherValidator(): other control is not found in parent group');
                }
                otherControl.valueChanges.subscribe(() => {
                    thisControl.updateValueAndValidity();
                });
            }

            if (!otherControl) {
                return null;
            }

            if (otherControl.value !== thisControl.value) {
                return {
                    matchOther: true
                };
            }

            return null;

        }
    }
}
表单验证服务具有以下方法:

public IsFieldValid(form: FormGroup, field: string){
    return !form.get(field).valid && form.get(field).dirty;
}

您的代码仅检查表单控件是否脏且无效。但您需要检查特定验证是否失败。因此,您需要传递一个额外的
错误
参数('required'、'minlength'等),并使用


如果custome验证器matchOther失败,您应该返回{matchOther:true}并检查
form.get(field).hasError('matchOther')

我回答这个问题有点晚了,但我找到了一个解决方案,这是我非常喜欢的Angle materials模块的一部分。如果使用“mat form field”实现字段,则可以使用包含带*ngIf的跨距的“mat error”轻松显示错误消息

我想我应该把它发布给其他试图实现验证器错误消息的人。它使HTML有点粗壮,但它看起来真的很好

<form [formGroup]="myForm" (ngSubmit)="submitForm()">
        <mat-form-field>
            <input matInput formControlName="user_input">
            <mat-error>
                <span *ngIf="myForm?.controls.user_input?.errors?.required">Required Field</span>
                <span *ngIf="myForm?.controls.user_input?.errors?.minLength">Minimum Length is 5</span>
            </mat-error>
        </mat-form-field>
</form>

必填字段
最小长度为5

文档可在此处找到:

在您可以使用的模板中


电子邮件是必需的

*ngIf=“username.errors.minlength”
*ngIf=“username.errors.required”
。无法直接在模板中链接。您将第一个条件放在显示最小长度消息的元素上,将第二个条件放在显示所需消息的元素上。如我链接到的文档所示。具体问题是什么?你的代码在哪里?我添加了代码,我希望它有意义。看来你还没有读过我的评论。您的代码仅检查表单控件是否脏且无效。但是您希望检查特定验证是否失败:
返回form.get(field).dirty&&form.get(field).errors.required
以检查所需的验证。您不可能从
无效的
布尔值(只能是true或false)中知道哪些验证失败。不过,还有一件事,如果我有自定义验证程序,它没有显示,我尝试使用预构建验证程序。正如您在emailConfirm中看到的,我有
MatchOtherValidator.Validate('email')]
并且方法启动,我如何在hasError中检查pass custom validator?@AmelSalibasic如果custome validator matchOther失败,您应该返回{matchOther:true}并检查form.get(field).hasError('matchOther');请注意,
mat form field
mat error
未内置在angular中,它们是单独的angular Material UI包的一部分。“奥普没有提到他在用它。”亚历山大·阿巴库莫夫:接得好。我将更改那里的措辞。
public IsFieldValid(form: FormGroup, field: string){
    return !form.get(field).valid && form.get(field).dirty;
}
form.get(field).hasError(error)
<form [formGroup]="myForm" (ngSubmit)="submitForm()">
        <mat-form-field>
            <input matInput formControlName="user_input">
            <mat-error>
                <span *ngIf="myForm?.controls.user_input?.errors?.required">Required Field</span>
                <span *ngIf="myForm?.controls.user_input?.errors?.minLength">Minimum Length is 5</span>
            </mat-error>
        </mat-form-field>
</form>