Angular 表单的自定义验证 - 模糊

Custom validation on Angular Form - on blur

在 Angular 中,我正在尝试验证模糊字段的值。我有一个客户列表,我想检查字段中的模型值是否在我的客户列表中。如果不是,我想将有效性设置为false。

我知道 ng-model-options="{updateOn: 'blur'} 存在,但是,我不能使用它,因为该字段是预先输入的,所以它必须根据模型进行更新。验证是需要在模糊上发生的事情。

答案好像是:

  1. 将其作为控制器中的函数编写,并像在指令中一样使用 $setValidity。使用 ng-blur 触发输入字段中的功能。

    -但是,我将 运行 保留在示例中,其中自定义验证(如果模型值与列表中的值不匹配,则使字段无效)仅作为指令编写。是否有编写为函数的自定义验证示例?

  2. 写一个只在模糊时触发的指令。

但是,我找不到执行这些操作的示例。有没有人有自定义验证的示例作为函数或仅在字段模糊时更新的指令?

我发现这个 link 对自定义验证很有帮助,但我仍然对函数和指令之间的区别有同样的问题:How to add custom validation to an AngularJS form?

我使用 ui-bootstrap 进行预输入,对您的验证进行了大量控制 ui-bootstrap typeahead

编辑-代码示例

<input type="text" ng-model="selected" typeahead="state for state in states | filter:$viewValue | limitTo:8" class="form-control" typeahead-no-results="$scope.matchFail"> <div ng-show="$scope.matchFail">Not on list!!</div>

当您选择不在列表中的值时,将显示 div

作为我们最近一直在做的事情:

<form name='vm.formName' id='vm.formName' novalidate>
  <input type='text' id='textField' name='textField' ng-blur='vm.blurMethod()' ng-model='vm.model.text' />
  // The submit is only here for show;
  <input type='submit' id='submit' ng-click='vm.submitForm()' />
</form>

在控制器中:

blurMethod() {
  if (this.formName.textField.$viewValue !== myArbitraryValue) {
    // $setValidity called on the form, setting the textfield's validity to false
    // then you can have your own validators show the error in the template
    this.formName.$setValidity('textField', false);
  }
}

我想不出来了,明天早上会看看它是否反映了我们一直在使用的东西。现在更新了 $setValidity 调用。

这假设您使用的是 controllerAs: 'vm' 语法,这就是表单名称为 'vm.formname' 而控制器使用 'this'.

的原因