angularjs-表单自定义验证

自定义验证
ctrl.$setValidity(‘field’,true/false)

ngMessages用于简化验证提示信息代码的编写
1.导入angular-messages.js
2.添加依赖‘ngMessages’
3.设置ng-messages=”form.name.$error4.设置ng-message=”required”

通过验证用户名的唯一性:

app.directive('ensureUnique', function () {
    return {
        require:'ngModel',
        link: function (scope, element, attrs, ctrl) {
            console.log(attrs.ngModel);
            //通过检测属性ngModel的名称的变化,动态查询是否存在相应的用户名
            scope.$watch(attrs.ngModel, function (newVal,oldVal) {
                if(['Tom','Jerry'].indexOf(newVal) != -1){ //新注册的用户名在其中
                    ctrl.$setValidity('unique',false);
                }
                else{
                    ctrl.$setValidity('unique',true);
                }
            })
        }
    }
})


<form name="myForm" ng-submit="submit()" novalidate>
  <input type="text" ng-model="username" name="username" ng-minlength="5" ng-maxlength="15" required ensure-unique />
  <div class="invalid" ng-messages="myForm.username.$error" ng-messages-include="error-messages.html">

  </div>

  <input type="submit"/>
</form>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值