AngularJS 表单验证小结

注:本文所述的表单验证即AngularJS自带的表单验证,无需引入第三方的插件

一、常用的验证特性标签

1.非空

为input加入一个required属性即可,例如:

 <input type="text" required>

2.最大长度,最小长度

为input加上ng-maxlength或者ng-minlength属性,并且属性值为需要设置的长度,例如:

<input type="text" ng-minlength="5" ng-maxlength="20" />

3.邮箱

将input的type设置为email即可,例如:

<input type="email"/>

4.数字

与邮箱同理,将type设置为number<input type="number"/>

5.URL

将type设置为url

6.正则表达式

使用ng-pattern来指定正则表达式,例如:<input type="text" ng-pattern="/[a-zA-Z]/" />

还有非常多的特性,等待大家探索......

二、验证消息的展示

1.$invalid和$valid

例:<span ng-show="model.$invalid" class="text-danger">error message.</span>

 表单name.字段名.$invalid 或者  表单name.字段名.$valid 中获得验证是否通过,最终来决定验证消息是否显示,如果是获取表单中所有元素是否通过验证,直接使用 表单name.$invalid 或者 表单name.$valid

$valid是通过验证时为true,不通过为false,$invalid是没有通过验证时为true,不通过为false.

2.$error

$error中会包含比较详细的错误信息,包括错误类型,错误消息,错误的字段等等~

下面是我抓取的一段整个form表单的$error信息,具体的可以参考一下angular的文档,这里我也没有去深入研究。

{"required":[{"$validators":{},"$asyncValidators":{},"$parsers":[],"$formatters":[null],"$viewChangeListeners":[],"$untouched":true,"$touched":false,"$pristine":true,"$dirty":false,"$valid":false,"$invalid":true,"$error":{"required":true},"$name":"bookName","$options":null},{"$validators":{},"$asyncValidators":{},"$parsers":[],"$formatters":[null],"$viewChangeListeners":[null],"$untouched":true,"$touched":false,"$pristine":true,"$dirty":false,"$valid":false,"$invalid":true,"$error":{"required":true},"$name":"isbn","$options":null},{"$validators":{},"$asyncValidators":{},"$parsers":[],"$formatters":[null],"$viewChangeListeners":[],"$untouched":true,"$touched":false,"$pristine":true,"$dirty":false,"$valid":false,"$invalid":true,"$error":{"required":true},"$name":"author","$options":null},{"$validators":{},"$asyncValidators":{},"$parsers":[],"$formatters":[null],"$viewChangeListeners":[],"$untouched":true,"$touched":false,"$pristine":true,"$dirty":false,"$valid":false,"$invalid":true,"$error":{"required":true},"$name":"price","$options":null},{"$validators":{},"$asyncValidators":{},"$parsers":[],"$formatters":[null],"$viewChangeListeners":[],"$untouched":true,"$touched":false,"$pristine":true,"$dirty":false,"$valid":false,"$invalid":true,"$error":{"required":true},"$name":"pressDate","$options":null},{"$validators":{},"$asyncValidators":{},"$parsers":[],"$formatters":[null],"$viewChangeListeners":[],"$untouched":true,"$touched":false,"$pristine":true,"$dirty":false,"$valid":false,"$invalid":true,"$error":{"required":true},"$name":"description","$options":null}]}

$error的用法同$valid,需要获取哪个字段的就是 表单name.字段name.$error

 

posted @ 2016-05-11 17:38  人生无赖  阅读(739)  评论(0编辑  收藏  举报