【问题标题】:AngularJS UI Select ValidationAngularJS UI 选择验证
【发布时间】:2020-11-08 16:46:11
【问题描述】:

您好,我正在开发一个 AngularJS 应用程序,该应用程序有一个字段可以从远程源中选择多个电子邮件地址。我正在为该字段使用 Angular UI Select。用户还可以输入不存在的有效电子邮件。问题是如何限制用户输入无效的电子邮件。

这里是示例代码sn-p:

<ui-select multiple tagging tagging-label="('new' email)" ng-model="emails" theme="bootstrap" sortable="true" required>
<ui-select-choices repeat="email in emails track by emailId" refresh="refreshEmailAddresses($select.search)"
refresh-delay="0">
</ui-select-choices>
</ui-select>

【问题讨论】:

标签: angularjs ui-select


【解决方案1】:

在您的模板中添加以下代码。

<ui-select multiple tagging 
           ng-model="multipleName" 
           ng-change="checkValidMail()" 
           sortable="true" 
           style="width: 263px;" 
           title="Enter Name" 
           on-select="afterSelection($item);" 
           on-remove="afterRemoving($item); checkValidMail();">
   <ui-select-match placeholder="Enter Name...">{{$item | limitTo:25}}
   </ui-select-match>
   <ui-select-choices repeat="personName in multipleName |filter:$select.search">
        {{personName}} 
   </ui-select-choices>
</ui-select>
<span class="c-red" ng-if="errorMail"> You entered a wrong mail id..! </span>
    

在您的控制器中添加以下代码。

checkValidMail = function() {
     var exp = /^[_a-z0-9]+(\.[_a-z0-9]+)*@[a-z0-9-]*\.([a-z]{2,4})$/;
     for(var i of $scope.multipleName) {
         if(exp.test(i)) {
             $scope.errorMail = false;
         } else {
             $scope.errorMail = true;
             break;
         }
      }
 }

【讨论】:

    【解决方案2】:

    您可以使用正则表达式:

    $scope.validEmail = /^(([^<>()\[\]\.,;:\s@\"]+(\.[^<>()\[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i;
    

    之后,将ngPattern 添加到您的模块中并将其包含在您的指令中:

    <ui-select multiple tagging tagging-label="('new' email)" ng-model="emails" theme="bootstrap" sortable="true" ng-pattern="validEmail" required>
      <ui-select-choices repeat="email in emails track by emailId" refresh="refreshEmailAddresses($select.search)"
      refresh-delay="0">
      </ui-select-choices>
    </ui-select>
    

    【讨论】:

    【解决方案3】:

    您可以在输入上使用 $watch 并使用正则表达式或其他东西在手表中进行验证。也许是这样的,希望它为您指明正确的方向:

      $scope.$watch('multipleDemo.emails', function(n, o) {
        if (!n) {
          return;
        }
        //validation here drop into n
        if (n === expression) {
          $scope.emails.push(n);
        } else {
           var index = $scope.emails.indexOf(n);
           $scope.emails.slice(index,1);
        }
      });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-21
      • 2015-06-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多