2

I am trying to validate email in php using ereg, where I am not allowed to enter more than two dots after @ and it can't begin with any special character, how can I do it.

function chk($a)
{

$pattern = "^([A-Za-z0-9\.|-|_]{1,60})([@])";
$pattern .="([A-Za-z0-9\.|-|_]{1,60})(\.)([A-Za-z]{2,3})$";

  if (!@ereg($pattern, $a))
     return false;
  else
       return true;
}
Hunterr
  • 553
  • 1
  • 8
  • 28
  • can you try this `$pattern .="([A-Za-z0-9\.|-|_]{1,60})([\.{2}])([A-Za-z]{2,3})$";` – Pratik Soni Jul 15 '15 at 19:12
  • Thanks but, it still returns valid. – Hunterr Jul 15 '15 at 19:15
  • Let me try and get you better solution. – Pratik Soni Jul 15 '15 at 19:17
  • 1
    Can you provide a sample input and why are you using ereg? `Warning This function has been DEPRECATED as of PHP 5.3.0. Relying on this feature is highly discouraged.` I think `preg_match` should work for you. – chris85 Jul 15 '15 at 19:17
  • apple_boy@gmail.com is valid apple_boy@gmail.co.uk too is valid but, apple_boy@gmail.co.uk.xyz is invalid. I am aware of it, but I need it for my understanding. – Hunterr Jul 15 '15 at 19:21
  • It is perfectly valid to have email addresses at a subdomain, i.e. someone@subdomain.example.co.uk. Therefore, your “only two dots after the @ sign” validation will flag false positives. If this is a lesson in using regular expressions, it’s a poor one. – Martin Bean Jul 15 '15 at 19:23
  • Btw, any amount of dots are valid in email addresses. For training purpose ok, but don't exclude legit users from any service you plan to offer. Like `test@eu.west.lol.com` is super valid. – Daniel W. Jul 15 '15 at 19:23
  • That's not true in general. Employees at many UK schools have addresses of the form `employee@school.region.sch.uk`, for instance. –  Jul 15 '15 at 19:25
  • Thanks to all for the suggestions, probably informations. It may be valid to have any number of dots after the @ sign, but for self understanding, what shall be the proper regex to accept only two dots that was the basic question. – Hunterr Jul 15 '15 at 19:30

3 Answers3

3

Please don't roll your own email validation.

if(filter_var($email, FILTER_VALIDATE_EMAIL) === true){
    return true;
} else {
    return false;
}
cmorrissey
  • 8,493
  • 2
  • 23
  • 27
2
preg_match("/^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/",'test@test.co.in.');
Pratik Soni
  • 2,498
  • 16
  • 26
0
function custom_email_confirmation_validation_filter( $your_email ) {
   if(!preg_match("/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/ix", $your_email )){ 
        return 'invalid';
    }
    
  if( substr_count($your_email, '.') > 3){
    return 'invalid 1';
  }
  
  return 'valid';
}

echo custom_email_confirmation_validation_filter('golapk.kkk.khazi@gmail.com');