欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

angular 基于ng-messages的表单验证实例

程序员文章站 2024-02-04 18:34:04
最近在学习angular,那么今天也算个学习笔记吧! html

最近在学习angular,那么今天也算个学习笔记吧!

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个中英文字符,aaa会重名,必填"
        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>
</div>

ng-messages="myform.myname.$error" 给出错误类型(required, char, exist, minlength)

error.html

<span ng-message="required">必填</span>
<span ng-message="char">非法字符</span>
<span ng-message="exist">名称已存在</span>
<span ng-message="minlength">太短了</span>

directive name-check 利用ngmodel 的$validators,& $asyncvalidators 添加自定义验证

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;
      }
    }
  }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。