ihtus
ihtus

Reputation: 2811

Regex validate items with delimiter

I am using this regex for email validation in php (based on here)

^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$;

My question is how can I validate input that is a list of emails separated by a delimiter. Let's say delimiter is "," or ";" or ", " or "; ".

I suppose i should add something like that

(\s*(;|,)\s*|\s*$)

but it doesn't work...

Upvotes: 1

Views: 146

Answers (3)

Gilles Quénot
Gilles Quénot

Reputation: 185106

Validating an email for real is better done by a module than a short regex. See http://www.ex-parrot.com/pdw/Mail-RFC822-Address.html

But fortunately, php have a validator :

<?php
$email_a = '[email protected]';
$email_b = 'bogus';

if (filter_var($email_a, FILTER_VALIDATE_EMAIL)) {
    echo "This (email_a) email address is considered valid.";
}
if (filter_var($email_b, FILTER_VALIDATE_EMAIL)) {
    echo "This (email_b) email address is considered valid.";
}
?>

See http://php.net/manual/en/filter.examples.validation.php

Upvotes: 3

Lawrence Cherone
Lawrence Cherone

Reputation: 46602

Dont use regex to validate emails, PHP has a function for this filter_var():

$email = '[email protected]';
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
  //valid
}else{
  //not
}

You can adapt this code and use explode(',',$email) to validate multiple emails.

Upvotes: 1

abathur
abathur

Reputation: 1047

At the risk of giving you an answer you can't use if you're only accepting a pure regex solution, for a few reasons I would recommend using explode with your delimiter and proceed to iterate over the array and validate each email in turn:

  1. Your regex and the code handling it will be simplified.

  2. Your regex will only have to handle the general use case of emails and can be a general re-usable operation any time you need to validate an email address. It will also be simple to swap the regexp operation out for a call to a library meant for email validation, or any other custom validator.

  3. It will be easier to handle possible related necessities, like indicating in your output which email failed to validate, or accepting all addresses which validated and discarding those that didn't.

Upvotes: 0

Related Questions