最近在学习angular,那么今天也算个学习笔记吧!
html
ng-messages="myForm.myName.$error" 给出错误类型(required,char,exist,minlength)
error.html
required">必填
名称已存在
directive name-check 利用ngModel 的$validators,& $asyncValidators 添加自定义验证
nameCheck.$inject = ['HttpService','$q'];
原文链接:https://www.f2er.com/js/39523.htmlfunction nameCheck(HttpService,$q){
var NAME_REG = /^[a-zA-Z\u4e00-\u9fa5]+$/;
return {
restrict: 'A',require: 'ngModel',link:function($scope,element,attrs,ctrl){
ctrl.$validators.char = function(modelValue,viewValue) {
var value = modelValue || viewValue;
if(!NAME_REG.test(value)){
return false;
}
return true;
};
ctrl.$asyncValidators.exist = function(modelValue,viewValue){
var value = modelValue || viewValue;
var deferred = $q.defer();
HttpService.get('api/users/' + value).then(function(res) {
if(res.isExist){
deferred.reject(false);
}
deferred.resolve(true);
})
return deferred.promise;
}
}
}
}