admin管理员组

文章数量:1410674

I am using ng-tags-input, and trying to modify the input so that only tags which are permitted can be added. For example, an array contains 'Tag1' but not 'T1', and so when 'T1' is entered in the input bar it is not accepted, but 'Tag1' is because it is 'permitted'.

Thanks.

I am using ng-tags-input, and trying to modify the input so that only tags which are permitted can be added. For example, an array contains 'Tag1' but not 'T1', and so when 'T1' is entered in the input bar it is not accepted, but 'Tag1' is because it is 'permitted'.

Thanks.

Share Improve this question edited May 11, 2015 at 16:38 scniro 17k8 gold badges66 silver badges107 bronze badges asked Jul 7, 2014 at 20:15 BackusBackus 431 silver badge6 bronze badges 2
  • What defines a valid tag? Do you have a list of them? Or does it need to match a particular pattern? What have you tried? – Anthony Chu Commented Jul 7, 2014 at 21:20
  • A valid tag is a valid country code (US, GB, CA...) which I have a full string array of, each just a two character string. I want to restrict the possible tags in the input so that the only two char strings that can bee tags are valid country codes, as in they exist in the country code array that I have. – Backus Commented Jul 8, 2014 at 20:19
Add a ment  | 

2 Answers 2

Reset to default 4

Currently there's no built-in way to perform such validation. But I think you can use a different approach:

  • Use the autoComplete directive to provide the user with the list of valid country codes;
  • Set the addFromAutopleteOnly option to true, so only tags ing from the autoplete list will be allowed.

HTML

<tags-input ng-model="countryCodes" add-from-autoplete-only="true">
   <auto-plete source="loadCountryCodes($query)"></auto-plete>
</tags-input>

Working Plunk

Just in case are trying to put a check for Email ID, below is the code. In case of other validation, please change the validation function accordingly.

HTML:

<tags-input ng-model="tagList" add-on-space="true" add-on-ma="true" add-on-blur="true" add-on-enter="true" on-tag-added="tagAdded($tag);" placeholder="Add ma separated email id's" ></tags-input>

Controller:

$scope.tagList = ['[email protected]', '[email protected]'];
$scope.tagAdded=function(tag){    
    var textEntered=tag.text;       
    var isVaildEmail=validateEmail(tag.text);
    console.log($scope.tagList);
    if(isVaildEmail){
       console.log(true); //do something
    }
    else{
       $scope.tagList.splice($scope.tagList.indexOf(tag),1); //remove the aded tag from ng-model of the input. i.e. tagList
    } 
}
function validateEmail(email) {
    var re = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
    return re.test(email);
}

本文标签: javascriptHow can I add or remove a tag with ngtagsinput within a functionStack Overflow