Q:

PHP program to validate an email address

belongs to collection: PHP Miscellaneous

0

Suppose there is a form floating where every user has to fill his/her email ID. It might happen that due to typing error or any other problem user doesn't fill his/her mail ID correctly. Then at that point, the program should be such that it should print a user-friendly message notifying the user that address filled is wrong. This is a simple program and can be done in two ways in PHP language.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Method 1: Naive approach

There is a filter called FILTER_VALIDATE_EMAIL which is in-built in PHP and validates mail ID.

The function filter_var() is also used in this program which takes two arguments. The first is the user mail ID and the second is the email filter. The function will return a Boolean answer according to which we can print the message of our desire.

Program:

<?php

    $email = "info@includehelp.com";
    if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
         echo '"' . $email . ' " is valid'."\n";
    }
    else {
         echo '"' . $email . ' " is Invalid'."\n";
    }

    $email = "inf at includehelp.com";
    if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
         echo '"' . $email . ' " is valid'."\n";
    }
    else {
         echo '"' . $email . ' " is Invalid'."\n";
    }
    
?>

Output:

"info@includehelp.com " is valid
"inf at includehelp.com " is Invalid

Method 2: Separating strings

How a normal human being validates some email addresses? The human observes some pattern in the string as well as some special characters while checking the validation of an email. The same can be done through programming. An email ID should necessarily have the character '@' and a string '.com' in a specific order. A function called preg_match() will be used for checking this order and characters.

<?php
    // A functios is created for checking validity of mail
    function mail_validation($str) {
        return (!preg_match("/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/ix", $str)) ? FALSE : TRUE;
    }
    
    // Taking user input of email ID
    $a=readline('Input an email address: ');
    if(!mail_validation($a))
    {
        echo "Invalid email address.";
    }
    else{
        echo "Valid email address.";
    }
?>

Output:

RUN 1:
Input an email address: info@includehelp.com
Valid email address.

RUN 2:
Input an email address: info@includehelp
Invalid email address.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

PHP Miscellaneous

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to detect search engine bots with PHP?... >>
<< Find remote IP address in PHP...