如何自定义验证添加到AngularJS形式? [英] How to add custom validation to an AngularJS form?

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

问题描述

我有一个输入字段,并添加要求属性和这样的验证设置形式。但对于一些领域,我需要做一些额外的验证。我将如何挖掘,以验证该的FormController 控件?

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?

自定义验证可能是这样的:如果这3个字段填写,则该字段是必需的,需要以特定方式进行格式化。

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".

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

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.

其实,从控制器(同步,同时也保持的FormController )为无效标志字段可能是我需要最简单的场景的东西,把工作完成,但我不知道该怎么做。

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.

推荐答案

编辑:关于ngMessages(> = 1.3.X)添加以下信息

由于这是顶级的结果之一,如果你谷歌角表单验证,目前,我想另一个答案添加到此的人从那里进来

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.

有在的FormController。$ setValidity的方法,但这并不看起来像一个公共的API,所以我宁可不使用它。

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.

要做到自定义验证,如果你不希望使用角度的UI与其他答案建议,你可以简单地推出自己的验证指令。

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>

注意:在1.2.X它可能是preferrable替换 NG-如果 NG-节目上方

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

下面是一个强制性的 plunker链接

另外,我写了眼前这个课题进入更详细一点的几个博客条目:

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

角表单验证

自定义验证指令

您现在可以使用ngMessages模块,而不是ngShow显示您的错误消息。它将实际上任何工作,它不必是一个错误消息,但这里的基本知识:

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. 包含&LT;脚本SRC =角messages.js&GT;&LT; / SCRIPT&GT;

  2. 参考 ngMessages 在你的模块声明:

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


  • 添加适当的标记:

  • 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>
    


  • 在上面的标记, NG-消息=personForm.email。$错误基本上指定了上下文NG-消息子指令。然后 NG-消息=必需的 NG-消息=电子邮件指定有关这方面的属性来观看。 更重要的是,他们还指定的顺序来检查它们在。它找到那就是truthy列表中的第一个胜利,它会显示其他的该消息并没有。

    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.

    和一个 plunker为ngMessages例如

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

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