vvr
vvr

Reputation: 466

How to validate multiple email addresses in a text box or text area at a time using php

I am using this regular expression for validating one email.

/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/

How to validate multiple email addresses in a text box or text area with comma (,) and semicolon (;) separated at a time using PHP.

example: [email protected],[email protected];[email protected],[email protected]

Upvotes: 0

Views: 3898

Answers (2)

David Richard
David Richard

Reputation: 356

$emails = preg_split('[,|;]',$_POST['emails']);
foreach($emails as $e){
    if(preg_match('/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/',trim($e)) == 0){
        echo($e ."is not a valid email address");
    }
}

Should break your incoming emails into an array of emails. Then will go through each email and check the regular expression. Will output that an email is invalid as it finds them. Feel free to replace the echo with whatever you want the code to do if an email is invalid. Edited: breaks both commas and semicolons

Edit:Regular expression was changed. (Sorry I hadn't checked it before posting.)

Upvotes: 4

mario
mario

Reputation: 145482

Okay, here is an howto on how to transform your regex into matching a list of something: validate comma separated list using regex

The simple approach is splitting up your string, and then validating each entry (either is inexact, as commas are actually allowed in addresses):

 $list = str_getcsv($emails);   // or preg_split on commas
 foreach ($list as $mail) {
     if (!filter_var($mail, FILTER_VALIDATE_EMAIL)) {
         return false;
     }
 }

Or you use the Using a regular expression to validate an email address and exchange the last line (?&address)/x for:

 ^\s* (?&address) (\s*,\s* (?&address) )* \s* $ /x

Upvotes: 2

Related Questions