【问题标题】:AngularJS Validation adding "valid" class value even when $valid returns false即使 $valid 返回 false,AngularJS 验证也会添加“有效”类值
【发布时间】:2017-07-26 21:15:43
【问题描述】:

背景

我正在维护一个现有的 AngularJS 应用程序。

我有一个基于正则表达式模式进行验证的文本字段。

<input type="text" class="validate" name="recipientContact"  id="recipientContact" ng-model="orderdata.recipient_contact" ng-pattern="/[(]([0-9]{3})[)]\s([0-9]{3})[-]([0-9]{4})/g" required>

正则表达式验证本身正在工作。我确认 $valid 在输入有效值时返回 true,在输入无效值时返回 false。

<p ng-bind="orderForm.recipientContact.$valid && ordersaveFlag"></p> //returns true for valid values, returns false for invalid values

问题

但是,问题在于即使输入了无效值,Angular 也会添加“有效”类属性值。

这不会影响功能(输入无效值时表单会停止),但会影响样式(输入元素边框颜色变为绿色而不是红色)。

当我对元素进行“检查”时,我确认正在动态添加“有效”类。即使 $valid 为假,为什么还要添加“有效”类? Angular“知道”文本字段无效,它应该添加“无效”类,这样样式才能正确应用。

当输入 invalid 值(所有动态添加的类属性值)时,检查在实时页面上显示的内容如下。它应该添加类属性值“无效”而不是“有效”。

<input type="text" class="validate ng-invalid ng-touched ng-dirty ng-valid-parse ng-valid-required ng-invalid-pattern valid" name="recipientContact"  id="recipientContact" ng-model="orderdata.recipient_contact" ng-pattern="/[(]([0-9]{3})[)]\s([0-9]{3})[-]([0-9]{4})/g" required>

如何进一步调查此问题?谢谢!

【问题讨论】:

    标签: javascript angularjs validation


    【解决方案1】:

    我能够用 ng-class 条件解决问题。

    <input type="text" ng-class="{'valid' : orderForm.recipientContact.$valid, 'invalid' : orderForm.recipientContact.$invalid}" name="recipientContact"  id="recipientContact" ng-model="orderdata.recipient_contact" ng-pattern="/[(]([0-9]{3})[)]\s([0-9]{3})[-]([0-9]{4})/g" required>
    

    这篇文章很有帮助:

    AngularJS | Conditional Class using ng-class

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-09-25
      • 2021-11-30
      • 1970-01-01
      • 2017-03-31
      • 2014-02-17
      • 2013-01-16
      相关资源
      最近更新 更多