PHP: Form validation

trevor1940
trevor1940 used Ask the Experts™
on
Hi
I have a couple of questions regarding form validation

First is there a way to validate a name field

$FormError=0;
$name = filter_input(INPUT_POST, 'name');

if(empty($name) || strlen($name >250)){
  echo "Name Error";
$FormError++;
}

Open in new window


Second this isn't working

// HTML

<input type="text" name="nickName" placeholder="bondj007">

// PHP
$NickName = filter_input(INPUT_POST, 'nickName', FILTER_VALIDATE_REGEXP,array("options" => array("regexp"=>'/*\d{3}$/')));
            if (empty($NickName )  ){ 
             // no NickName this OK as not mandatory but if submited must have 3 numbers at the end
              }
           elseif(strcmp($NickName, "bondj007")){
// this isn't working
              echo"Are you really James Bond?";
                $FormError++;

           } 
         else{
              echo"Nick name Valid";
         }

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Most Valuable Expert 2017
Distinguished Expert 2018

Commented:
First is there a way to validate a name field

Validate how - you need to specify a rule. I am guessing that you want a M < length > N and maybe some sort of Regular Expression check on chars - but we would need to know what

Secondly - when you say not working
a) What did you expect
b) What did you observe

Easier to answer if you can give us some clues on the above.
Most Valuable Expert 2018
Distinguished Expert 2018
Commented:
Firstly, what do you mean by validate! You can validate any data in PHP as long as you know what you want to validate against.

Looking at your code you're trying to make sure the $_POST['name'] isn't empty and is less than 250 characters. You have a bracket in the wrong place in your strlen() function. It should be:

if( empty($name) || strlen($name) >250 ) {

As for your second part, there are a few issues. The regex for a string ending in 3 characters looks a little off. Try this:

"/^.+?\d{3}$/"

filter_input will return false if it fails the regex check, so if someone enter "Nick", the $nickName will be 'false'.

You're also using the strcmp() function. This is a binary comparison, and you should probably be using an equality operator (==).

A quick example of what you probably need:

if ( ! empty($_POST['nickName']) ):

    $pattern = "/^.+?\d{3}$/";
    $nickName = filter_input(INPUT_POST, 'nickName', FILTER_VALIDATE_REGEXP, array("options" => array("regexp" => $pattern)));

    if ( ! $nickName): // we failed the regex validation
        echo "Nickname doesn't contain 3 numbers";
    else: // we passed the regex validation
        if ($nickName == "bondj007"):
            echo "Are you really James Bond?";
        else:
            echo "Nickname is valid";
        endif;
    endif;

endif;

Open in new window

Author

Commented:
Thanx Chris I'll test it tomorrow on the live  script I suspect some of your  points are due to typos

When I asked about validating a name I was hopping for how experts do it

$name ="Robert'); DROP TABLE Students;";

Open in new window


Probably isn't valid but bellow could be

$name="Chloé Double-Barrel O'Tool";

Open in new window



As for the 2nd part I was using === to compare the strings which seemed to fail  google suggested to use  strcmp()

The logic is if the user wishes to enter a Nick Name it has to end with 3 numbers but cannot be "bondj007"
Expert Spotlight: Joe Anderson (DatabaseMX)

We’ve posted a new Expert Spotlight!  Joe Anderson (DatabaseMX) has been on Experts Exchange since 2006. Learn more about this database architect, guitar aficionado, and Microsoft MVP.

Most Valuable Expert 2018
Distinguished Expert 2018

Commented:
No worries.

Don't believe everything you read on Google ;)

strcmp() does a binary comparison, so it's used for checking higher / lower, as in alphabetical. It will return -1 if str1 is less than str2, 1 if str1 is greater than str1 and 0 if they're equal. You were checking for a boolean, so if the strings matched, it would return 0, which equates to boolean false, so it's not the correct function to use. Just do a simple equality (==).

Still not sure what you mean by validate. Based on your example, I'm guessing Chloé Double-Barrel O'Tool (great name!) would be valid, so you wouldn't want to filter anything out.

If you're planning on doing any DB work with it, then you should be using a prepared statement, so apostrophes won't be an issue, and you should configure your whole app (php / html / db) to use utf8 encoding so the accented letters won't be an issue either. IMO - those 2 points are how Experts would generally deal with it as a good starting point :)

Author

Commented:
IMO - those 2 points are how Experts would generally deal with it as a good starting point

Thanx for the tip I guess was expecting something complex but that adherers  to the KISS principle which works for me

I'm assuming I put "header('Content-Type: text/html; charset=utf-8'); in my  PHP files will sort the encoding?
Most Valuable Expert 2018
Distinguished Expert 2018

Commented:
Regarding the header - it depends. If your PHP is outputting data that will be used in the HTML file, then it's the HTML that needs the encoding:

<head>
    <meta charset="utf-8">
    ...

If you're connecting to a database then you need to setup the connection to use utf8. For PDO, set it in the DSN:

$dsn = 'mysql:host=localhost;dbname=yourDb;charset=utf8mb4';

And for mysqli, set it on the connection:

$db = new mysqli($hostname, $username, $password, $database);
$db->set_charset("utf8");

You'll need to make sure your tables are setup to use utf8, and that's done at the mysql server level.

That should give you a good starting point for a utf8 compatible app.

Author

Commented:
Thanx Chris for help and the additional tips on UTF8

I've come to the conclusion you can't validate a name because there isn't any rules that govern names other than length but even that is arbitrary so as long as the name is handled as free text correctly the application should be OK

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial