Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect when text is entered into the textarea and change it correspondingly

I have a textarea where users can enter or paste email addresses of other people and send them an invite after pressing Submit button. Each email must be seperated with a comma and valid before the form is submitted - validation is taken care of by jQuery Validate plugin & multiemail method.

Problem

Some people paste email addresses directly from their email clients and those emails are often in a weird format - containing name and surname before the actual email, or the email is wrapped in < >. For example: "The Dude" <[email protected]>, "The Dudette" <[email protected]>

Question

What I want to do is to Extract all email addresses from bulk text using jquery, but I'm having problems integrating this piece of code to work with my textarea - I don't know where to start.

How could I use the code from the above answer to extract each email entered into the textarea after a comma is typed or when the focus is moved away from textarea? So if I paste "The Dude" <[email protected]> and type , after it or switch focus away, the entered value would change to [email protected].

like image 593
dTilen Avatar asked Mar 23 '23 04:03

dTilen


1 Answers

I'm guessing something like this :

var textarea = $('#emails');

textarea.on({
    keyup: function(e) {
        if (e.which === 188) check();
    },
    blur: check    
});

function check() {
    var val  = $.trim(textarea.val()),
        err  = '';

    if (!val.length) {
        err = 'No input ?';
        return;
    }

    var emails   = val.split(','),
        notvalid = [],
        temp     = [];

    $.each(emails, function(_,mail) {
        mail = $.trim(mail);
        if ( mail.length ) {
            var m = mail.match(/([a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+)/gi);
            if (m) {
                temp.push(m);
            }else{
                temp.push(mail);
                notvalid.push(mail)
            }
        }else{
            temp.push(mail);
        }
        if (notvalid.length) err = 'Not valid emails : ' + notvalid.join(', ');
    });

    $('#error').html(err);
    textarea.val((temp.length ? temp : emails).join(', '));
}

FIDDLE

like image 198
adeneo Avatar answered Apr 05 '23 23:04

adeneo