我看Angularjs的东西,实际工作上用到了自定义表单验证。在学习的过程中,看到了两种写法:
写法一:
这个写法来自
http://www.angularjs.net.cn/tutorial/4.html
var app = angular.module('form-example1', []);
var INTEGER_REGEXP = /^\-?\d+$/;
app.directive('integer', function() {
return {
require: 'ngModel',
link: function(scope, elm, attrs, ctrl) {
ctrl.$parsers.unshift(function(viewValue) {
if (INTEGER_REGEXP.test(viewValue)) {
// 验证通过
ctrl.$setValidity('integer', true);
return viewValue;
} else {
// 验证不通过 返回 undefined (不会有模型更新)
ctrl.$setValidity('integer', false);
return undefined;
}
});
}
};
});
写法二:
这个写法实现了 异步的表单验证
这个写法来自下面这个
https://blog.csdn.net/jax2000/article/details/51531493
'use strict';
angular.module('app', [])
.directive('phone', function ($q, $http) {
return {
require: 'ngModel',
link: function (scope, ele, attrs, ctrl) {
ctrl.$asyncValidators.phone = function (modelValue, viewValue) {
var d = $q.defer();
$http.get('phone.json')
.success(function (phoneList) {
if (phoneList.indexOf(parseInt(modelValue)) >= 0) {
d.reject();
} else {
d.resolve();
}
});
return d.promise;
}
}
}
})
.directive('username', function ($q, $http) {
return {
require: 'ngModel',
link: function (scope, ele, attrs, ctrl) {
ctrl.$validators.username = function (modelValue, viewValue) {
if (modelValue) {
return modelValue.length > 5 ? true : false;
};
return false;
}
}
}
})