<!DOCTYPE HTML> <html ng-app="myApp"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>无标题文档</title> <style> //验证通过不通过的样式 input.ng-valid{ border:1px green solid; background:green;} input.ng-invalid{ border:1px red solid; background:red;} </style> <script src="angular.min.js"></script> <script> var m1 = angular.module('myApp',[]); m1.controller('Aaa',['$scope',function($scope){ $scope.text = 'hello'; }]); </script> </head> <body> <div ng-controller="Aaa"> <form novalidate name="myForm"> //ng-model是将视图绑定Model(变量) <input type="text" name="myText" ng-model="text" required ng-minlength="5" ng-pattern="/^[a-zA-Z]+$/"> //通过名字来查找输入框 <div>{{ myForm.myText.$valid }}</div> //校验成功是true, <div>{{ myForm.myText.$invalid }}</div> //校验成功是false, <div>{{ myForm.myText.$pristine }}</div> //验证的值没有修改过为true修改后是false <div>{{ myForm.myText.$dirty }}</div> //验证值修改后为true没有修改为false <div>{{ myForm.myText.$error }}</div> //验证失败为false </form> </div> </body> </html>
<!DOCTYPE HTML> <html ng-app="myApp"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>无标题文档</title> <style> </style> <script src="angular.min.js"></script> <script> var m1 = angular.module('myApp',[]); m1.controller('Aaa',['$scope',function($scope){ $scope.regText = {//定义对象 regVal : 'default', regList : [ { name : 'default' , tips : '请输入用户名'}, { name : 'required' , tips : '用户名不能为空'}, { name : 'pattern' , tips : '用户名必须是字母'}, { name : 'pass' , tips : '√'} ] }; $scope.regPassword = {//定义对象 regVal : 'default', regList : [ { name : 'default' , tips : '请输入密码'}, { name : 'required' , tips : '密码不能为空'}, { name : 'minlength' , tips : '密码至少6位'}, { name : 'pass' , tips : '√'} ] }; $scope.change = function( reg , err ){//reg = "regText", err = {required: false, pattern: true} for(var attr in err){ if( err[attr] == true ){ $scope[reg].regVal = attr;//$scope[regText].regVal = attr; return; } } $scope[reg].regVal = 'pass';//$scope[regText].regVal = 'pass'; }; }]); </script> </head> <body> <div ng-controller="Aaa"> <form novalidate name="nForm"> <div> <label>用户名:</label> //nForm.nText.$error返回的值是{required: false, pattern: true}这种类型 <input type="text" name="nText" ng-model="regText.name" required ng-pattern="/^[a-zA-Z]+$/" ng-blur="change('regText',nForm.nText.$error)"> //提示信息遍历出来,|是管道符,filter是过滤器, : 是传参数,regText.regVal是传的参数, <span ng-repeat=" re in regText.regList | filter : regText.regVal "> {{ re.tips }} </span> </div> <div> <label>密码:</label> <input type="password" name="nPassword" ng-model="regPassword.name" required ng-minlength="6" ng-blur="change('regPassword',nForm.nPassword.$error)"> //提示信息 <span ng-repeat=" re in regPassword.regList | filter : regPassword.regVal "> {{ re.tips }} </span> </div> </form> </div> </body> </html>
本文转自农夫山泉别墅博客园博客,原文链接:http://www.cnblogs.com/yaowen/p/5741223.html,如需转载请自行联系原作者