2

I have a select2 box, an I was to limit this to accept only email addresses.

I am trying to do this by writing a custom formatSelection function, as

formatSelection: function(object, container){
        if(validateEmail(object.text)){
            return object.text;
        }
        else{
            return "";
        }
    }

I am expecting that returning an empty string would be enough to not show this input in select2, but I am getting an empty result.

shabda
  • 1,668
  • 1
  • 18
  • 28
  • Can you please create the fiddle? It would be more helpful to understand your problem. – IT ppl Mar 29 '14 at 04:53
  • what is a use of another aggs `container' ? – Anant Dabhi Apr 08 '14 at 06:11
  • For anyone reading this in the future, email regex validation is a very complex field: I would strongly suggest you don't roll your own. Inevitably, someone will enter a valid email which fails the regex, and that might hurt your objectives. – BenKoshy Feb 25 '20 at 23:38

5 Answers5

12

As of select2 4.0 +, just use the createTag function:

createTag: function(term, data) {
    var value = term.term;
    if(validateEmail(value)) {
        return {
          id: value,
          text: value
        };
    }
    return null;            
}

function validateEmail(email) {
    var re = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    return re.test(email);
}
Tunaki
  • 132,869
  • 46
  • 340
  • 423
Sagi
  • 1,612
  • 5
  • 20
  • 28
1

I have solved this. Just copy paste the code below and it will work smooth.

validate: function(value) {
            if(value && value.length != 0){
                var emailText = "";
                var isValidEmail = true;
                var isEmailLengthValid = true;
                for (var i in value) {
                    var email = value[i];
                    isValidEmail = validateEmail(email);
                    if(isValidEmail == false){
                        break;
                    }else{
                        emailText = (i == 0) ? emailText : ", " + emailText;
                        if(emailText.length > 250){
                            isEmailLengthNotValid = false;
                            break;
                        }
                    }
                }
                if(isValidEmail == false){
                    return 'Enter a valid email address';
                }else if(isEmailLengthValid == false){
                    return 'Maximum 250 characters allowed';
                }
            }
        }

Also add below function validateEmail() which uses regex to validate email string.

function validateEmail(email) { 
    var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    return re.test(email);
} 
Prateek Sharma
  • 269
  • 1
  • 7
  • Hi Prateek, could you please post a jsFiddle or explain a bit more on how to include the "validate:" in the Select2 javascript? I'm trying to do exactly this but the alerts won't fire when invalid email address are typed in – Chronix3 Sep 28 '14 at 09:47
  • Without your code, mine is simply: $('#emailAutoComplete').select2({ placeholder: "Please enter an email address", allowClear: true, tags:, tokenSeparators: [",", " "], minimumInputLength: 2 }); – Chronix3 Sep 28 '14 at 09:47
  • The above function says function statement requires a name [Why function statement requires a name?](http://stackoverflow.com/questions/8086696/why-function-statement-requires-a-name) – Basheer Kharoti Feb 10 '15 at 15:38
0

it isn't clear from your question where your data source is. if the data source is from an ajax call then you can do server side validation and only return the email addresses.

but i suspect that you want to accept user input and only of valid email addresses. The Select2 docs explain the createSearchChoice function in the initialization $opts. you could insert your validateEmail function here and decide if you want to accept the new answer or not.

you might even want to write to an external DOM element any errors you find so the user knows they have to go back and correct the invalid email address.

    //Allow manually entered text in drop down.
    createSearchChoice: function(term, data) {
        if ( $(data).filter( function() {
            return this.text.localeCompare(term) === 0;
        }).length === 0) {
            return {id:term, text:term};
        }
    },
xeo
  • 807
  • 2
  • 7
  • 25
0

i use select2 4.01

regex validator email

function isEmail(myVar){

    var regEmail = new RegExp('^[0-9a-z._-]+@{1}[0-9a-z.-]{2,}[.]{1}[a-z]{2,5}$','i');
    return regEmail.test(myVar);
}

i return only a text without id in the return json if it's no valid. in this cas, you can add alert no selectable.

createTag: function (params) 
{

                        if(!isEmail(params.term)){
                            return {
                                text: params.term,
                            };
                        }
                        return {
                          id: params.term,
                          text: params.term,
                        };

}

In your templateResult

function formatRepoReceiver (repo) {
      if (repo.loading) return repo.text;
        var markup =  "";
        if(typeof(repo.email) == 'undefined'){
           // >>>your Alert<<<<
          if(!isEmail(repo.text)){
            if(repo.text == ''){
                return null;
            }

            return 'Address email no valid';
          }  
          //----------------------------
          markup = "<div class='select2-result-repository clearfix'>"+
                        "<div class='select2-result-repository__meta'>" +
                            "<span>"+ repo.text +"</span> "+
                            "(<span>" + repo.text + "</span>)"+
                        "</div>"+
                    "</div";
      }
      else{
        markup = "<div class='select2-result-repository clearfix'>"+
                        "<div class='select2-result-repository__meta'>" +
                            "<span>"+ repo.name +"</span> "+
                            "(<span>" + repo.email + "</span>)"+
                        "</div>"+
                    "</div";
      }

      return markup;
    }
Kevin Detrain
  • 161
  • 1
  • 5
0
$('.select2-tokenizer').on('change', function() {

var num= this.value

if(!$.isNumeric(num)){

   $('option:selected',this).remove();
   Swal.fire({
                          icon: 'error',
                          title: 'Oops...',
                          text: 'Please enter an integer!'
                        })

} 
});