Skip to content Skip to sidebar Skip to footer

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 inp

Solution 1:

You could do like this.

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

Solution 2:

You can use trim and strlen php functions


Solution 3:

u can use $.trim() jquery function before to submit form.

var nowhitespace = $.trim($("#input").val());

Solution 4:

I think str_replace() is all you want. Or you could some javascript to prevent whitespace from being entered into the input field.

<?php
$s = str_replace(' ', '', $_POST['username']);
?>

If you're going to use trim(), don't forget about rtrim()


Post a Comment for "How To Check If Data Is Empty Or Whitespace Only In PHP"