如何向 AngularJS 表单添加自定义验证? [英] How to add custom validation to an AngularJS form?

查看:40
本文介绍了如何向 AngularJS 表单添加自定义验证?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过添加 required 属性等,我有一个包含输入字段和验证设置的表单.但是对于某些领域,我需要做一些额外的验证.我将如何利用"FormController 控制的验证?

自定义验证可能类似于如果填写了这 3 个字段,则该字段是必需的并且需要以特定方式进行格式化".

FormController.$setValidity 中有一个方法,但它看起来不像公共 API,所以我不想使用它.创建自定义指令并使用 NgModelController 看起来是另一种选择,但基本上需要我为每个自定义验证规则创建一个指令,这是我不想要的.

实际上,将控制器中的字段标记为无效(同时保持 FormController 同步)可能是我在最简单的情况下完成工作所需的东西,但我没有知道怎么做.

解决方案

在下方添加了有关 ngMessages (>= 1.3.X) 的信息.

标准表单验证消息(1.0.X 及更高版本)

由于这是 GoogleAngular Form Validation"的最佳结果之一,因此目前,我想为从那里进来的任何人添加另一个答案.

<块引用>

FormController.$setValidity 中有一个方法,但它看起来不像一个公共 API,所以我宁愿不使用它.

它是公开的",不用担心.用它.这就是它的用途.如果不打算使用它,Angular 开发人员就会在闭包中将其私有化.

要进行自定义验证,如果您不想像其他答案建议的那样使用 Angular-UI,您可以简单地推出自己的验证指令.

app.directive('blacklist', function (){返回 {要求:'ngModel',链接:功能(范围,元素,属性,ngModel){var blacklist = attr.blacklist.split(',');//对于DOM ->模型验证ngModel.$parsers.unshift(function(value) {var valid = blacklist.indexOf(value) === -1;ngModel.$setValidity('blacklist', valid);返回有效吗?值:未定义;});//对于模型 ->DOM 验证ngModel.$formatters.unshift(function(value) {ngModel.$setValidity('blacklist', blacklist.indexOf(value) === -1);返回值;});}};});

这是一些示例用法:

<input type="text" name="fruitName" ng-model="data.fruitName" blacklist="coconuts,bananas,pears" required/><span ng-show="myForm.fruitName.$error.blacklist">短语{{data.fruitName}}"被列入黑名单</span><span ng-show="myForm.fruitName.$error.required">必需</span><button type="submit" ng-disabled="myForm.$invalid">提交</button></表单>

注意:在 1.2.X 中,最好将 ng-if 替换为上面的 ng-show

这是一个强制性的 plunker 链接

另外,我已经写了一些关于这个主题的博客文章,其中详细介绍了一些:

角度表单验证

自定义验证指令

在 1.3.X 中使用 ngMessages

您现在可以使用 ngMessages 模块代替 ngShow 来显示错误消息.它实际上可以处理任何事情,它不一定是错误消息,但这是基础知识:

  1. 包含
  2. 在您的模块声明中引用 ngMessages:

    var app = angular.module('myApp', ['ngMessages']);

  3. 添加适当的标记:

    <input type="email" name="email" ng-model="person.email" required/><div ng-messages="personForm.email.$error"><div ng-message="required">required</div><div ng-message="email">无效的电子邮件</div>

</表单>

在上面的标记中,ng-message="personForm.email.$error" 基本上指定了 ng-message 子指令的上下文.然后 ng-message="required"ng-message="email" 指定要观看的上下文的属性.最重要的是,他们还指定了将它们签入的顺序.它在列表中找到的第一个真实"的人获胜,它将显示该消息,而不显示其他任何消息.

还有一个 ngMessages 示例的 plunker

I have a form with input fields and validation setup by adding the required attributes and such. But for some fields I need to do some extra validation. How would I "tap in" to the validation that FormController controls?

Custom validation could be something like "if these 3 fields are filled in, then this field is required and needs to be formatted in a particular way".

There's a method in FormController.$setValidity but that doesn't look like a public API so I rather not use it. Creating a custom directive and using NgModelController looks like another option, but would basically require me to create a directive for each custom validation rule, which I do not want.

Actually, marking a field from the controller as invalid (while also keeping FormController in sync) might be the thing that I need in the simplest scenario to get the job done, but I don't know how to do that.

解决方案

Edit: added information about ngMessages (>= 1.3.X) below.

Standard form validation messages (1.0.X and above)

Since this is one of the top results if you Google "Angular Form Validation", currently, I want to add another answer to this for anyone coming in from there.

There's a method in FormController.$setValidity but that doesn't look like a public API so I rather not use it.

It's "public", no worries. Use it. That's what it's for. If it weren't meant to be used, the Angular devs would have privatized it in a closure.

To do custom validation, if you don't want to use Angular-UI as the other answer suggested, you can simply roll your own validation directive.

app.directive('blacklist', function (){ 
   return {
      require: 'ngModel',
      link: function(scope, elem, attr, ngModel) {
          var blacklist = attr.blacklist.split(',');

          //For DOM -> model validation
          ngModel.$parsers.unshift(function(value) {
             var valid = blacklist.indexOf(value) === -1;
             ngModel.$setValidity('blacklist', valid);
             return valid ? value : undefined;
          });

          //For model -> DOM validation
          ngModel.$formatters.unshift(function(value) {
             ngModel.$setValidity('blacklist', blacklist.indexOf(value) === -1);
             return value;
          });
      }
   };
});

And here's some example usage:

<form name="myForm" ng-submit="doSomething()">
   <input type="text" name="fruitName" ng-model="data.fruitName" blacklist="coconuts,bananas,pears" required/>
   <span ng-show="myForm.fruitName.$error.blacklist">
      The phrase "{{data.fruitName}}" is blacklisted</span>
   <span ng-show="myForm.fruitName.$error.required">required</span>
   <button type="submit" ng-disabled="myForm.$invalid">Submit</button>
</form>

Note: in 1.2.X it's probably preferrable to substitute ng-if for ng-show above

Here is an obligatory plunker link

Also, I've written a few blog entries about just this subject that goes into a little more detail:

Angular Form Validation

Custom Validation Directives

Edit: using ngMessages in 1.3.X

You can now use the ngMessages module instead of ngShow to show your error messages. It will actually work with anything, it doesn't have to be an error message, but here's the basics:

  1. Include <script src="angular-messages.js"></script>
  2. Reference ngMessages in your module declaration:

    var app = angular.module('myApp', ['ngMessages']);
    

  3. Add the appropriate markup:

    <form name="personForm">
      <input type="email" name="email" ng-model="person.email" required/>
    
      <div ng-messages="personForm.email.$error">
        <div ng-message="required">required</div>
        <div ng-message="email">invalid email</div>
      </div>
    </form>
    

In the above markup, ng-message="personForm.email.$error" basically specifies a context for the ng-message child directives. Then ng-message="required" and ng-message="email" specify properties on that context to watch. Most importantly, they also specify an order to check them in. The first one it finds in the list that is "truthy" wins, and it will show that message and none of the others.

And a plunker for the ngMessages example

这篇关于如何向 AngularJS 表单添加自定义验证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆