The week ago I was programming my web application using PHP5.
There is two ways to validate email:
- On server side (using filter_var from PHP5)
- On client side (using input type email from HTML5)
PHP5 example
$email = "xpto@email.com";
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo "This ".$email." email address is considered valid.";
}
HTML5 example
<form action="file.php" method="post"> E-mail: <input type="email" name="useremail"><br> <input type="submit"> </form>
In my opinion it is better validate email on client side instead server side. So don't validate email on server side because it takes a lot work to warn user that has an invalid email address. With client side to validate email, it saves a lot work to warn user that has an invalid email address.
But if you are programming a web application using OOP, it is good idea to validate email from server side because you are not using form to validate email but you are using object, for example:
class User{
  private $name, email;
 
  public function __construct($name,$email){
   $this->name=$name;
   $this->email=validate($email);
  }
  
 private function validate($email){
  $mail = "";
  if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
   $mail = $email;
  }else{
    echo "This $email is not valid!";
   }
  return $mail;
 }
}
$user = new User("Peter","peter@xpto.com");//valid email
$user = new User("Paul","kjfddks");//prints "This kjfddks is not valid!"
 
 
No comments:
Post a Comment