标签:
注:本文所述的表单验证即AngularJS自带的表单验证,无需引入第三方的插件
为input加入一个required属性即可,例如:
<input type="text" required>
为input加上ng-maxlength或者ng-minlength属性,并且属性值为需要设置的长度,例如:
<input type="text" ng-minlength="5" ng-maxlength="20" />
将input的type设置为email即可,例如:
<input type="email"/>
与邮箱同理,将type设置为number<input type="number"/>
将type设置为url
使用ng-pattern来指定正则表达式,例如:<input type="text" ng-pattern="/[a-zA-Z]/" />
还有非常多的特性,等待大家探索......
例:<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.
$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
标签:
原文地址:http://www.cnblogs.com/baiyunchen/p/5482770.html