3

Hi I am working on an AngularJS app with a field to select multiple email addresses from a remote source. I am using Angular UI Select for that field. User can also enter a valid email which does not exist. The problem is how do I restrict the user from entering an invalid email.

Here is the sample code snippet:

<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>
arnabkaycee
  • 1,634
  • 13
  • 26

3 Answers3

1

Add the below code in your template.

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

Add the below code in your controller.

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;
         }
      }
 }
svarog
  • 9,477
  • 4
  • 61
  • 77
-1

You can use a Regex:

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

After that, add ngPattern to your modules and include it inside your directive:

<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>
ohboy21
  • 4,259
  • 8
  • 38
  • 66
  • Hi @gruberb. The solution is not working. Here's the updated plunkr : http://plnkr.co/edit/SlHqOqDfKAbaHFrYYp7f?p=preview – arnabkaycee May 06 '16 at 16:44
-1

You could use a $watch on the input and validate in the watch with the regex or something. Maybe something like this, hope it points you in the right direction :

  $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);
    }
  });
alphapilgrim
  • 3,761
  • 8
  • 29
  • 58