Reputation: 97
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]
.
Upvotes: 4
Views: 2763
Reputation: 7026
you can detect when an textarea is changed (or other input field) by using an eventhandler. Jquery supports multiple events (have a look here http://api.jquery.com/category/events/). In this particular case I should use the keyup event for triggering the extractEmails function. This way your extraction will be "live". However, it is also possible by catching a blur or change event.
With keyup eventhandler
$('#text').on('keyup',function(event) {
emails=extractEmails($(this).val());
$("#emails").text(emails);
});
function extractEmails (text)
{
return text.match(/([a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+)/gi);
}
Upvotes: 3
Reputation: 951
This will convert the entered text to emails when you either lose focus, or enter a comma, as you requested:
function extractEmails (text)
{
return text.match(/([a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+)/gi);
}
$("#emailtext").on('keypress blur', function(e) {
if (e.which === 44 || e.type =="blur")
{
$('#emails').text(extractEmails($("#emailtext").val()));
}
});
Here's the fiddle:
Upvotes: 1
Reputation: 318182
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(', '));
}
Upvotes: 3