Search code examples
phpvalidationemailphone-number

How to know which variable has a value and which one is null?


I need to validate an input which I will need to later check against a database for its presence in the table. The input either has to be a mobile number (all digits, 10 max len) or an email address. This below is what I did

<?php

$credential = '9999999999';

if (ctype_digit($credential)) {
        $mobile_number = $credential;
        echo 'Mobile: '. $mobile_number;
    } elseif (filter_var($credential, FILTER_VALIDATE_EMAIL)) {
        $email = $credential;
        echo 'Email: '.$email;
    }

output when $credential = '9999999999';

Mobile: 9999999999

output when $credential = 'abc@gmail.com';

Email: abc@gmail.com

Two questions,

  1. Is there a better way of doing it? Like, using preg_match.

  2. The above code manages to differentiate between an email and a mobile number which later I need to match against a database. In a real scenario, the input will be user-supplied, $credential = $_POST['credential']; and then either of two variable will be set accordingly. How do I know which of the two variable is set? If I am to match email to email column or mobile number to the mobile column, I need to know which of the two has value and which one is null.


Solution

  • filter_var($credential, FILTER_VALIDATE_EMAIL) is going to perform better than regex, because that is what it is specifically designed to do.

    As for the phone numbers, this seems a little undercooked or too strict. Many people add spaces, parentheses, hyphens, etc without much thought. It will only be irritating to be so strict on the phone number, I think. There are plenty of regex patterns on SO regarding phone number validation. Intimate knowledge of your expected phone number strings are required to answer this confidently. Are you expecting US numbers only? is this international? We don't know, so I can't say what is the best strategy.

    This will work:

    if (ctype_digit($credential) && strlen($credential)==10) {
        $mobile_number = $credential;
        echo 'Mobile: '. $mobile_number;
    } elseif (filter_var($credential, FILTER_VALIDATE_EMAIL)) {
        $email = $credential;
        echo 'Email: '.$email;
    }
    

    This will also work:

    if (preg_match('/^\d{10}$/',$credential)) {
        $mobile_number = $credential;
        echo 'Mobile: '. $mobile_number;
    } elseif (filter_var($credential, FILTER_VALIDATE_EMAIL)) {
        $email = $credential;
        echo 'Email: '.$email;
    }
    

    The speed differences between the two methods will be totally unnoticeable to your users. You should choose whichever approach you prefer personally.