PHP: Validate Email, Name, Price, Age using Regular Expression & filter_var

This article contains PHP code with regular expression to validate different numbers and strings. Integer validation can be done for validating age. Decimal validation can be done for validating price. Simple String validation can be done for validating name. Email validation can be done for validating email.

preg_match PHP function is used to perform the regular expression match.

Validate Name


function validateName($name) {
    if (preg_match("/^[a-zA-Z'. -]+$/", $name)) {
        return true;  
    }
    return false;
}

Validate Age


function validateAge($age) {
    if (preg_match("/^[0-9]+$/", $age)) {
        return true;  
    }
    return false;
}

Validate Price

Allowing only 2 digits after dot. Price can be decimal or without decimal. 9 and 9.99 = both are true.


function validatePrice($price) {
    if (preg_match("/^[0-9]+(\.[0-9]{2})?$/", $price)) {
        return true;  
    }
    return false;
}

Validate Email


function validateEmail($email) {
    if (preg_match("/^[_a-z0-9-+]+(\.[_a-z0-9-+]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/", $email)) {
        return true;  
    }
    return false;
}

If you are using PHP 5.2 and above then you can use filter_var function to validate name, age and email. This has made validation a lot more easier task. We don’t need to write any regular expression code while using filter_var function.

Validate Email


function validateEmail($email) {
    if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
        return true;  
    }
    return false;
}

In the above example, filter “FILTER_VALIDATE_EMAIL” is used to validate email. Similarly, there are different other filters to validate integer, boolean, URL, IP, etc.

FILTER_VALIDATE_BOOLEAN
FILTER_VALIDATE_FLOAT
FILTER_VALIDATE_INT
FILTER_VALIDATE_IP
FILTER_VALIDATE_URL

Hope it helps.
Thanks.