使用基于多个条件的ng-messages显示验证消息

时间:2016-01-19 11:07:52

标签: javascript angularjs validation ng-messages

我使用angular ng-messages显示验证消息

请考虑以下代码:

<ul ng-messages="formToValidate.fieldToValidate.$error" ng-messages-multiple>
    <li ng-message="pattern">Invalid pattern</li>
    <li ng-message="minlength, maxlength">Should contain no less than 7 and no more than 100 chars</li>
    <li ng-message="!pattern && !minlength && !maxlength && onlyAfterAllOtherPassedValidation">
        This validation message is shown only when all the other validations have passed and validation  fails on onlyAfterAllOtherPassedValidation
    </li>
</ul>

我想仅在所有其他验证都已通过且仅在AfterAfterAllOtherPassedValidation上验证失败时才显示最后一条验证消息。 我不知道是否有可能将复杂的条件传递给ng-message 只要我仍然可以使用ng-messages

,欢迎任何建议和变通方法

2 个答案:

答案 0 :(得分:3)

您可以在持有消息的元素上使用ng-if,例如

<li ng-if="!formToValidate.fieldToValidate.$error.required && !formToValidate.fieldToValidate.$error.minLength && !formToValidate.fieldToValidate.$error.maxLength" ng-message="onlyAfterAllOtherPassedValidation">
    This validation message is shown only when all the other validations have passed and validation  fails on onlyAfterAllOtherPassedValidation
</li>

答案 1 :(得分:0)

JonMac1374 提出的解决方案当然有效。但是,一劳永逸地解决这个问题会更好。我建议你注意指令use-form-error。它有助于建立自己的支票。

jsfiddle上的实例。

<form name="ExampleForm">
  <label>Password</label>
  <input ng-model="password" name="password" minlength="2" pattern="^\d*$" required use-form-error="onlyAfterAllOtherPassedValidation" use-error-expression="!ExampleForm.password.$error.required && !ExampleForm.password.$error.minlength && !ExampleForm.password.$error.pattern"
  />
  <pre>{{ExampleForm.password.$error|json}}</pre>
  <div ng-messages="ExampleForm.password.$error" ng-messages-multiple="true" class="errors">
    <div ng-message="required">
      Your required is wrong
    </div>
    <div ng-message="pattern">
      Your pattern is wrong
    </div>
    <div ng-message="minlength">
      Your minlength is wrong
    </div>
    <div ng-message="onlyAfterAllOtherPassedValidation">
      Your onlyAfterAllOtherPassedValidation
    </div>
  </div>
</form>