hellzone
hellzone

Reputation: 5246

Regular expression for email addresses before @ symbol

I want to a regular expression to check user email addresses first part(before @ symbol).

Only characters numbers and "." symbol is valid. I tried something but it is not enough.

Here is my expression but problem is user can submit multiple dots like "example..test", "ex...amp..le".

"/^[a-zA-Z0-9.]+$/"

Edit: I dont want to allow underlines or something like that.

Upvotes: 0

Views: 1187

Answers (4)

Muran
Muran

Reputation: 65

Try this one:

"/^[a-zA-Z0-9]+(\.[a-zA-Z0-9_-]+)*$/"

Hyphens and underline must be supported and email must first begin with an alphanumeric character.

Upvotes: 0

adesst
adesst

Reputation: 307

You could try this

'/^[a-zA-Z0-9]+\.?[a-zA-Z0-9]+@/'

Here are some outputs:

$a = "[email protected]"
var_dump( preg_match('/^[a-zA-Z0-9]+\.?[a-zA-Z0-9]+@/', $a));
int(0)
$b = "[email protected]";
var_dump( preg_match('/^[a-zA-Z0-9]+\.?[a-zA-Z0-9]+@/', $b));
int(1)
$c = "[email protected]";
var_dump( preg_match('/^[a-zA-Z0-9]+\.?[a-zA-Z0-9]+@/', $c));
int(0)
$d = "[email protected]";
var_dump( preg_match('/^[a-zA-Z0-9]+\.?[a-zA-Z0-9]+@/', $d));
int(0)
$e = "[email protected]";
var_dump( preg_match('/^[a-zA-Z0-9]+\.?[a-zA-Z0-9]+@/', $e));
int(1)
$f = "[email protected]";
var_dump( preg_match('/^[a-zA-Z0-9]+\.?[a-zA-Z0-9]+@/', $f));
int(0)

Upvotes: 0

Ja͢ck
Ja͢ck

Reputation: 173562

Your specific case

To disallow repeated characters, you can use a negative assertion:

if (preg_match('/(?!.*\.\.)^[a-z0-9.]+$/', $inbox_name)) {
    // valid, probably
}

This allows a period as the first character though, which is not allowed in an email address, so you have to refine it further:

if (preg_match('/(?!.*\.(\.|$))^[a-z0-9][a-z0-9.]*$/', $inbox_name)) {
    // valid, probably
}

Explanation:

  1. Don't allow a period followed by another period or end of subject;
  2. String must start with a letter or digit;
  3. Starting character may be followed by letters, digits or periods.

Old answer

Use filters instead of trying to roll your own email address validation:

var_dump(filter_var('[email protected]', FILTER_VALIDATE_EMAIL)); 
// bool(false)

var_dump(filter_var('[email protected]', FILTER_VALIDATE_EMAIL)); 
// string("[email protected]")

Afterwards you still have no guarantee that the email address will actually work until you attempt an email delivery (and even then it may be a false positive).

I dont want to allow underlines or something like that.

That argument is just nonsensical; they're valid in an email address and you really have no reason to block it beyond personal preference.

Upvotes: 2

vks
vks

Reputation: 67968

^(?=[^.]*\.[^.]*$)[a-zA-Z0-9.]+$

You can try this.This will allow only one ..

$re = "/^(?=[^.]*\\.[^.]*$)[a-zA-Z0-9.]+$/m";
$str = "asdasd.asdasd.\nasdsad.asdasd\nasdsadsad.asdasd.sa.d.";

preg_match_all($re, $str, $matches);

Upvotes: 1

Related Questions