You have a DOM element with a list of e-mail addresses and you would like to clean the list up. You want to be left with valid e-mail addresses only. The element could be a form field - use type=val, or other type of element - use type=html or type=text. The following jQuery plugin will help you accomplish the clean up.
- (function( $ ) {
- $.fn.evalidate = function( type ) {
- return this.each( function () {
- var $this = $(this);
- var str = ($.inArray(type, ['text','html','val']) != -1) ? $this[type]() : "";
- if(str.length > 0)
- {
- var eArr = (str.indexOf(',') > -1) ? str.split(',') : str.split();
- str = $.grep(eArr, function(v,i) { return (/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/).test(v); }).join(',');
- if($.inArray(type,['text','html','val']) != -1)
- {
- $this[type](str);
- }
- }
- });
- };
- })( jQuery );
Usage: $(selector).evalidate('val') cleans up a form field of invalid e-mail addresses while $(selector).evalidate('val').val() cleans up and returns the cleaned-up list.
See it in action here: