AngularJS实现表单验证
2019-07-15 11:10:10 来源:易采站长站 作者:王旭
<input
type="email" name="email" ng-model="myEmail" ng-minlength="3" ng-maxlength="50" required />
<div style="color:red" ng-messages="mainForm.email.$error" ng-messages-multiple ng-messages-include="validateTemplate/email.html">
</div>
</p>
<p>
<input type="submit" ng-disabled="mainForm.$invalid" />
</p>
</form>
并不复杂,我们再加点东西。
为了让提示更友好(?)一些,我们试试实现光标离开后出现提示的效果。
这时候用指令(directive)会方便很多,在这里先涉及一点和指令相关的内容。
先运行起来再说:
var myApp = angular.module('myApp',[])
.controller('validationController', ['$scope',function($scope) {
$scope.user = 'Kavlez';
$scope.email = 'sweet_dreams@aliyun.com';
}])
.directive('hintOnBlur', [function() {
return {
require: 'ngModel',
link: function(scope, element, attrs, ctrl) {
ctrl.focused = false;
element.bind('focus', function(evt) {
scope.$apply(function() {ctrl.focused = true;});
}).bind('blur', function(evt) {
scope.$apply(function() {ctrl.focused = false;});
});
}
}
}]);
此处我们用focused来判断光标是否在某个属性上,当使用了hintOnBlur指令的对象上发生focus或blur事件时focused的状态发生变化。
表单也跟着改变一下,使用方法如下:
<form ng-controller="validationController" name="mainForm" >
<p>Email:
<input type="email" name="email" ng-model="myEmail" ng-minlength="3" ng-maxlength="50" required hint-on-blur />
- 热点聚合:













闽公网安备 35020302000061号