PHP empty field validation

I have a registration form where users have to enter an address there. I am using PHP for validation and am currently validating that the field is not empty. Here is my code:

if (empty($_POST['address'])) {
    $msg = 'You must enter an address' ;
} else {
    $address = mysqli_real_escape_string($dbc, strip_tags(trim($_POST['address']))) ;
}

      

Now the problem is that the user enters the "blank" space by pressing the spacebar, the checked validation passes. I need a way to make sure that the user actually typed a city, and not just a space or a couple of spaces.

+3


source to share


4 answers


You are already using trim()

in insert, why not call it once at the beginning and check that value?



$user_address = trim($_POST['address']);

if (empty($user_address)) {
    $msg = 'You must enter an address' ;
} else {
    $address = mysqli_real_escape_string($dbc, strip_tags($user_address)) ;
}

      

+4


source


if (empty($_POST['address']) || strlen(trim($_POST['address']))==0){
    $msg = 'You must enter an address' ;
}else {
    $address = mysqli_real_escape_string($dbc, strip_tags(trim($_POST['address']))) ;
}

      



Trim the value.

0


source


You need to consider regular expressions. I would start using the split: command split(' ', $address)

.
From now on, you can add one additional operator else if

to test and see if the resulting string is empty.
BUT, more importantly, you now have the tools to test the whole address bar to see if it contains: a two-letter status code followed by a comma, and a 5 (or 9) digit zip code. (I can be more specific if you like.)

0


source


if($_POST['submit']){
    $address = $_POST['address'];

    if (empty($address)) {
        echo "You must enter an address";
    } else {
        $address = mysqli_real_escape_string($dbc, strip_tags($user_address)) ;
    }
}

      

You can echo immediately send a message if the address field is empty.

also $_POST['submit']

is to determine if the user will click the submit button

0


source







All Articles