MD-chips电子邮件验证

时间:2018-10-19 12:32:08

标签: javascript html angularjs

md-chips电子邮件验证

如何为md-chips创建电子邮件验证?我的下面的表达式不起作用,因为每当我键入内容时,就会调用ng-keypress指令。

建议?

 <div class="row">
   <div class="col-md-12" ng-cloak="">
     <md-context class="md-padding">
       <md-chips md-separator-keys="ctrl.customKeys" ng-keypress="ctrl.validateEmail()" ng-model="ctrl.ConfiguracaoRegra.Emails" md-max-chips="20" placeholder="Inserir um email..." ng-required="true" type="email"></md-chips>
       </md-context>
   </div>
 </div>

   vm.validateEmail = function (keyEvent) {
    var emailValue = angular.element(".md-input").val();
    var reg = /^[_a-z0-9]+(\.[_a-z0-9]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/;
    if (reg.test(emailValue)) {
        vm.isEmailValid = true;
    } else {
        vm.isEmailValid = false;
    }
};

2 个答案:

答案 0 :(得分:1)

您应该使用ng-change指令代替ng-keypress,或将md-on-addmd-on-remove结合使用(请参阅https://github.com/angular/material/issues/3580#issuecomment-347052946

答案 1 :(得分:1)

我的解决方案是:创建一个javascript函数,在其中评估是否输入了ENTER并使用正则表达式('/ ^ [_ a-z0-9] +(。[_ a-z0-9] +)* @ [ a-z0(9)] +(。[A-z0-9-] +)*(。[Az] {2,4})$ /'),通过test()方法进行验证。

  function validateEmail(x) {
            if (event.which === 13) {
                var emailValue = x;
                var reg = /^[_a-z0-9]+(\.[_a-z0-9]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/;
                if (!reg.test(emailValue)) {                                        
                    toastr.error("Digite um email válido!");                    
                    vm.ConfiguracaoRegra.Emails.pop();
                }
            };

    };
<md-chips md-on-add="ctrl.validateEmail($chip)" ng-model="ctrl.ConfiguracaoRegra.Emails" md-max-chips="20" placeholder="Inserir um email..." type="email" required></md-chips>