Search code examples
phptrim

How to stop user from entering only space in input PHP?


I am creating a social site and in the registration code someone can enter only spaces in the input fields.

I don't want them to enter any spaces in the fields except for the password one.

I have tried a bunch of things, empty, trim, htmlentities !trim and some more I forgot. None of them worked. Some of them gave the first name the value of 1.

What am I missing?

Below is a list of things I have tried (not at the same time).

$first_name = trim(strip_tags(filter_var($_POST['first_name'], FILTER_SANITIZE_STRING)));
str_replace('  ', ' ', $first_name);

if (empty($first_name)) {
    echo "Fill in first name to sign up";
}
if (!ctype_alnum($first_name)) {
    echo "Invalid first name, it only may contain letters or digits";
} 

$first_name = $_POST['first_name'] ?? '';

if (empty($first_name)) {
    echo "Fill in first name to sign up";
}
if (!ctype_alnum($first_name)) {
    echo "Invalid first name, it only may contain letters or digits";
} 

$first_name = htmlentities(trim(strip_tags(filter_var($_POST['first_name'], FILTER_SANITIZE_STRING)));

if (empty($first_name)) {
    echo "Fill in first name to sign up";
}
if (!ctype_alnum($first_name)) {
    echo "Invalid first name, it only may contain letters or digits";
} 


Solution

  • Use regular expressions. The following checks it to be at least 5 symbols and contain just letters and digits;

    $firstName = trim($_POST['first_name']);
    
    if (!preg_match("/^[a-zA-Z0-9]{5,}$/", $firstName)){
      echo 'Invalid';
    }
    

    More information on preg_match() can be found here.