15

I have the following jQuery Validation Plugin:

<script type="text/javascript" src="/requires/js/jquery.min.js"></script>
<script type="text/javascript" src="/requires/js/jquery.validate.js"></script>
<script type="text/javascript"> 
    $(document).ready(function() {
        $("#form").validate({
            rules: {
                name: {
                    required: true,
                    minlength: 2
                },
                email: {
                    required: true,
                    email: true
                },
                emails: {
                    required: true,
                    email: true
                }
            },
            messages: {
                name: {
                    required: "Je bent vergeten om je naam in te vullen.",
                    minlength: "Je bent vergeten om je naam in te vullen."
                },
                email: {
                    required: "Je bent vergeten om je emailadres in te vullen.",
                    email: "Het opgegeven emailadres is niet geldig."
                },
                emails: {
                    required: "Je bent vergeten om het emailadres van je vriend(in) in te vullen.",
                    email: "Je moet een geldig e-mailadres van je vriend(in) invullen."
                }
            }
        });
    }); 
</script>

<form id="form" method="post">
Jouw naam: <input type="text" name="name"><br />
Jouw e-mailadres: <input type="text" name="email"><br />
Het e-mailadres van je vriend(in): <input type="text" name="emails"><br />
<input type="submit" value="Verstuur">
</form>

By value emails people must can give multiple emailaddresses like test@test.com;test2@test.com or test@test.com,test@test2.com

When you do this, the validation plugin gives the error: Je moet een geldig e-mailadres van je vriend(in) invullen.

How can I solve this problem?

Leniel Maccaferri
  • 100,159
  • 46
  • 371
  • 480
Arthur
  • 233
  • 2
  • 4
  • 13

3 Answers3

51

Here's a custom made function added with the help of the addMethod:

jQuery.validator.addMethod(
    "multiemail",
     function(value, element) {
         if (this.optional(element)) // return true on optional element 
             return true;
         var emails = value.split(/[;,]+/); // split element by , and ;
         valid = true;
         for (var i in emails) {
             value = emails[i];
             valid = valid &&
                     jQuery.validator.methods.email.call(this, $.trim(value), element);
         }
         return valid;
     },

    jQuery.validator.messages.email
);

Here's a jsFiddle that shows you how to use the multiemail custom method:

http://jsfiddle.net/leniel/xFphm/7/

Leniel Maccaferri
  • 100,159
  • 46
  • 371
  • 480
0

Custom made function with message inside

<script>    
jQuery.validator.addMethod("custom_method_one", function (value, element) {
    if (this.optional(element)) {
    return true;
    }

    var emails = value.split(','),
    valid = true;

    for (var i = 0, limit = emails.length; i < limit; i++) {
    value = emails[i];
    valid = valid && jQuery.validator.methods.email.call(this, value, element);
    }

    return valid;
    }, "Invalid email format: please use a comma to separate multiple email addresses.");

$('#form').validate({
 "emails": {  required:true,custom_method_one: true }   
})
</script>

<form method="post" id="form" name="form" action="">
 <input type="text" name="emails" id="emails" placeholder="(eg:abc@incipio.com,xyz@ncpo.com,....)"/>

</form>
Mahendra Jella
  • 5,450
  • 1
  • 33
  • 38
0

I may have over-engineered this, but I wanted to be able to paste multiple email addresses directly from the likes of Outlook, where the addresses may also contain the name of the recipient:

"Firstname Lastname" <email@address.com>; "Dud Address" <not-a-real-email-for-some-reason>; "Another Recipient" <another@address.com>

I also wanted to validate each address and tell the user which specific address is failing if one of them fails.

/**
 * The regular expression used to split emails,
 * where more than one email can be passed.
 * @type {RegExp}
 */
const emailSplitterRegex = /\s*?[;,]+\s*?/;

/**
 * The regular expression used to filter out
 * emails from email client strings that can include
 * the name of the recipient also.
 *
 * @type {RegExp}
 */
const outlookEmailStringSplitterRegex = /['"]?(\w+(?:\s+\w+)*)?['"]?\s*<?(\b[^\s]+@[\w.-]+\.[a-zA-Z]{2,4}\b)/g;

/**
 * Checks to see if complex email strings from email clients like Outlook,
 * that format the string like "Firstname Lastname" <email@address.com>
 * are valid emails by stripping away everything except the email itself.
 *
 * @param obj
 * @param email
 * @param element
 * @returns {boolean|*}
 */
function emailStringIsValid(obj, email, element){
    // Run the string thru the outlook email string splitter regex
    let matchesObject = email.matchAll(outlookEmailStringSplitterRegex);

    // Convert the RegExpStringIterator to an array
    let matches = [...matchesObject];

    if (matches.length) {
        //if the string is an outlook email string ("Name" <email@address.com>)

        //strip away everything but the email address itself
        email = matches[0].pop();
    }

    // trim whitespaces
    email = email.trim();

    // ignore empty strings
    if(!email.length){
        return true;
    }

    // Run the validator on the email address
    return $.validator.methods.email.call(obj, $.trim(email), element);
}

/**
 * Returns a custom error message for email strings. Particularly useful
 * for when multiple emails are passed and the error message should only
 * reference the email that is invalid.
 *
 * @param params
 * @param element
 * @returns {string}
 */
function emailsErrorMessage(params, element) {
    var emails = $(element).val().split(emailSplitterRegex);
    switch (emails.length) {
        case 0:
            return "Please enter at least one email address.";
        case 1:
            return "Please enter a valid email address.";
        default:
            for (let email of emails) {
                if(!emailStringIsValid(this, email, element)){
                    // Ensure brackets aren't treated as tags
                    email = email.replace(/</g, "&lt;");
                    email = email.replace(/>/g, "&gt;");

                    // Return an error message
                    return `${email} is not a valid email address.`;
                }
            }
            break;
    }
}

/**
 * Custom validator for when multiple emails can be passed, separated by
 * commas or semicolons.
 */
$.validator.addMethod("emails", function (value, element, params) {
    // Split the email string
    var emails = value.split(emailSplitterRegex); // split element by , and ;

    for (let email of emails) {
        // for each email
        if (!emailStringIsValid(this, email, element)) {
            //if a single email is invalid, return the whole string as invalid
            return false;
        }
    }

    return true;
}, emailsErrorMessage);
dearsina
  • 4,774
  • 2
  • 28
  • 34