当前位置: 移动技术网 > IT编程>脚本编程>AngularJs > AngularJS实现表单验证功能详解

AngularJS实现表单验证功能详解

2017年12月12日  | 移动技术网IT编程  | 我要评论

在ng中,针对表单和空间提供了属性,用于验证控件交互的状态

布尔类型:

ng-valid 表单通过验证时设置
ng-invalid 表单未通过验证时设置
ng-pristine 表单没有改动时设置
ng-dirty 表单有改动时设置

对象:

$error

注意事项:

①给表单以及表单组件 加上name属性
②给需要用到的表单组件 ,加上ngmodel
③属性的用法
myform.t_age.dirty/pristine/valid/invalid/$error

案例如下

<!doctype html>
<html ng-app="myapp">
<head lang="en">
 <meta charset="utf-8">
 <title></title>
 <script src="js/angular.js"></script>
</head>
<body>

<div ng-controller="myctrl">
 <form name="myform" ng-submit="submitinfo()">
 <input type="text" name="t_name"
   ng-model="username" required/>
 <span ng-show="myform.t_name.$error.required">
  姓名不能为空
 </span>
 <br/>
 <input type="text" name="t_age"
   ng-model="userage" required/>
 <span ng-show="myform.t_age.$invalid">验证失败</span>
 <span ng-show="myform.t_age.$pristine">没有输入过</span>

 <br/>
 <input
  ng-disabled="myform.$invalid"
  type="submit" value="提交"/>
 </form>
</div>

<script>
 var app = angular.module('myapp', ['ng']);

 app.controller('myctrl', function ($scope) {
 $scope.submitinfo = function () {
  console.log($scope.username,$scope.userage);
 }
 });
</script>
</body>
</html>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网