3

I have a enrollment form where users have to input there address. I am using PHP for validation and currently I check to make sure 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 is the user enters in a "blank" space by pressing the spacebar the filed passes validation. What I need is a way to make sure the user actually typed in a city and not just a blank space or a couple of blank spaces.

1
  • 1
    Just trim variable before you validate it Commented Mar 25, 2012 at 23:21

4 Answers 4

4

You already use trim() on the insert, why not call it once in the beginning, and test 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)) ;
}
Sign up to request clarification or add additional context in comments.

Comments

0
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.

1 Comment

. is not the member access operator in PHP, and strings have no properties in PHP, and that condition is incorrect regardless. Try strlen(trim($_POST['address'])) === 0.
0

You need to consider regular expressions. I would start off using a split command: split(' ', $address).
From that point, you can add one extra else if statement to test and see if the resultant string is empty.
BUT, more importantly, you will now have the tools to test the entire address string to see if it contains: a two letter state code followed by a comma, and a 5(or9) digit zip code. (I can be more specific if you like.)

Comments

0
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 the message if the field address is empty

also the $_POST['submit'] is to determine if the user click the submit button

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.