Angular Form Verification instance based on ng-messages, angularng-messages
I have been studying angular recently, so I should take a study note today!
Html
<Div class = "form-group" ng-class = "{'has-error': myForm. myName. $ touched & myForm. myName. $ invalid} "> <label class =" col-xs-2 control-label "> name </label> <div class =" col-xs-6 "> <input type =" text "class =" form -control "name =" myName "ng-model =" formData. username "placeholder =" 2-10 Chinese and English characters, aaa will be renamed, mandatory "name-check minlength =" 2 "maxlength =" 10 "required> </div> <div class =" col-xs-4 form-control-static text-danger "ng-messages = "myForm. myName. $ error "ng-messages-include =" demos/form/error.html "ng-show =" myForm. myName. $ touched "> </div>
Ng-messages = "myForm. myName. $ error" indicates the error type (required, char, exist, minlength)
Error.html
<Span ng-message = "required"> required </span> <span ng-message = "char"> invalid character </span> <span ng-message = "exist "> the name already exists </span> <span ng-message =" minlength "> too short </span>
Directive name-check use ngModel's $ validators, & $ asyncValidators to add custom Verification
app.directive('nameCheck', nameCheck);nameCheck.$inject = ['HttpService', '$q'];function 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; } } }}
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.