【问题标题】:Reactive Forms How to show one error message at a time?反应式表单如何一次显示一条错误消息?
【发布时间】:2019-04-11 01:04:29
【问题描述】:

我使用 Angular 7 并创建了一个响应式表单。输入字段email 设置了两个验证器,如下所示:

email: ['', [Validators.email, Validators.pattern('^[\\w._]+@company(.com|.go|.jet)')]],

两个验证器在模板中都有 2 条错误消息:

<label for="email" class="error-msg" *ngIf="authForm.get('email').hasError('email')  && hideFocus">Your email is invalid</label>
<label for="email" class="error-msg" *ngIf="authForm.get('email').hasError('pattern')  && hideFocus">Only emails ending with .com .go and .jet are allowed</label>

当用户在输入字段中键入时,两个错误会同时显示。

如何一次显示一条错误消息?有可能吗?

【问题讨论】:

    标签: javascript angular typescript angular-reactive-forms angular7


    【解决方案1】:

    逻辑运算符在这里会很有帮助。您可以检查一个错误是否无效而另一个错误是否有效。理论可能有点混乱,下面是一个例子:

    <label for="email" class="error-msg" *ngIf="authForm.get('email').hasError('email')  && hideFocus">Your email is invalid</label>
    <label for="email" class="error-msg" *ngIf="!authForm.get('email').hasError('email') && authForm.get('email').hasError('pattern')  && hideFocus">Only emails ending with .com .go and .jet are allowed</label>
    

    我还没有使用响应式表单,所以您需要正确使用上述语法,我使用ngForm。这背后的简单逻辑是检查一个错误是否无效,另一个是否有效,一次显示一个错误。

    非常感谢使用正确语法的编辑。

    【讨论】:

      【解决方案2】:

      如果生成了两个错误(因为输入不满足任何一个验证规则),您可以实现一个 ngIf-else 开关以首先显示您想要的任何错误。 An example of this can be found here.

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-04-10
        • 1970-01-01
        • 2012-06-04
        • 2019-03-13
        相关资源
        最近更新 更多