1

Everybody, I need To allow just string and numbers and dots "." in my email

'email' => 'required|string|email|unique:users|not_regex:/^.+$/i|regex :/^.+@.+$/i',

My Code Here is not allowing for "." i ned to allow just "." and block others like [# / \ $%^&* etc]

user3783243
  • 5,368
  • 5
  • 22
  • 41
  • 2
    Why not just allow all possible emails? Regex is not the correct tool. – Andreas Mar 06 '19 at 19:12
  • @Andreas i have done that but i need to block some things like / and # So all i need to do to accept just numbers and text and dots in my email – Kareem Elsharkawy Mar 06 '19 at 19:13
  • 1
    If you done it correctly then there shouldn't be a need for regex. http://php.net/manual/en/function.filter-var.php – Andreas Mar 06 '19 at 19:15

1 Answers1

1

You actually don't need a regex nowadays to validate a string consisting of an email address that should only include letters, numbers, and the @ and dot symbols. PHP allows for proper validation when you apply filter_var() twice, first to sanitize the data and then again to validate it, as follows:

<?php
// Variables to check
$emailA = "john1.doe@example.com";
$emailB = "john1.doe@example#.com";

// Remove all illegal characters from email
$emailValid = filter_var($emailA, FILTER_SANITIZE_EMAIL);
$emailInvalid = filter_var($emailB, FILTER_SANITIZE_EMAIL);

// Validate e-mail
if (filter_var($emailValid, FILTER_VALIDATE_EMAIL)) {
    echo("$emailValid is a valid email address"),"\n";
} else {
    echo("$emailValid is not a valid email address");
}
if (filter_var($emailInvalid, FILTER_VALIDATE_EMAIL)) {
    echo("$emailInvalid is a valid email address");
} else {
    echo("$emailInvalid is not a valid email address");
}

See live code

Note, if this code seems familiar, I admit that I modified the example given here :)

However if you insist on using a regex, here is one way to do so:

<?php

$emailA = "john1@here.com";
$emailB = "john1@here#.com";

function validateEmail( $email ){
$regex =  "/^[a-zA-Z0-9.]+@[a-zA-Z0-9.]+\.[a-zA-Z]{2,4}/";
$error =   "\nOnly letters, numbers, dot and @ are allowed"; 

echo (preg_match($regex,$email))?  "$email is valid\n" : "$error - $email is invalid\n";

return true;
}

validateEmail( $emailA );
validateEmail( $emailB );

See live code

It might seem kind of odd to have validateEmail() return true whether an email is valid or invalid. The return value can be useful if you need to verify that this function actually executed; see example here.

slevy1
  • 3,797
  • 2
  • 27
  • 33