Search code examples
phphtmlwhitespaceremoving-whitespace

How to check if data is empty or whitespace only in PHP


I have an input field that needs a username. The scenario is, how can i prevent user from providing whitespace or whitespaces in the that field? I already added required in the input field so i can prevent user from leaving it blank.

<input type="text" name="username" required>

but what if the user puts whitespace or as many whitespace as he can, is there any possible way i can detect this and throw error to the user?

in my php file i already have

if(empty($_POST['username'])){
echo "Username should not be empty!";
}

but this will fail because of the whitespaces the users put in the input field.


Solution

  • You could do like this.

    if(isset($_POST['username']))
    {
        if(strlen(trim($_POST['username'])) == 0){
            echo "Username should not be empty!";
        }
    }
    

    In the modern PHP it can be shorter

    if (!trim($_POST['username'] ?? '')) {
        echo "Username should not be empty!";
    }
    

    or, if you need to assign $_POST['username'] to a variable

    $username = trim($_POST['username'] ?? '');
    if(!$username) {
        echo "Username should not be empty!";
    }