angular表单验证

来源:互联网 发布:怎么惩罚淘宝卖家 编辑:程序博客网 时间:2024/05/16 00:39

表单验证很简单,要三点需要做的:

  1. 控制表单是否能提交
  2. 显示验证提示信息
  3. 自定义验证规则
第一点:控制表单是否可以提交
可以使用formName.$valid(有效为true)或formName.$invalid(无效为true)来控制提交按钮,formName为表单名称
例如
                    <form ng-submit="submit()" name="dataForm" novalidate>                    <label class="item item-input">                        <span class="input-label">产品编号</span>
                        <span class="input-label" ng-show="dataForm.barcode.$error.required">此项必填</span>                        <span class="input-label" ng-show="dataForm.barcode.$error.minlength">长度不够</span>                        <input type="text" name="barcode" ng-model="product.barcode" required ng-minlength="3">                    </label>                    <label class="item item-input">                        <span class="input-label">产品名称</span>                        <input type="text" ng-model="product.productName">                    </label>                    <button ng-disabled="!dataForm.$valid" class="button button-block button-positive" type="submit">                        提交                    </button>                    </form>
第二点:显示验证提示信息
这个也很简单,只需给input元素加上验证规则,然后通过formName.inputName.patternName(表单名称.文本框名称.验证规则)就可以得出是否验证通过,再通过ng-show就可以控制提示信息的显示和隐藏,有多少提示规则就写多少,angular会根据你的验证规则的顺序依次判断和显示。
第三点:自定义验证规则
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;        }      });    }  };});
使用以上代码就行了,这个不需要解释把。

0 0
原创粉丝点击