简体   繁体   中英

How would you improve this form validation code?

I need to validate a form. This is some server side validation that checks if required fields are filled out, emails are valid, numeric and alpha numeric fields don't contain rogue characters.

I would like some feedback on how to improve the code to be more reliable and terse.

<?php

// current state
$valid  = true;

// post data collection
$name   = "John Doe";
$email  = "user@gmail.com";
$age    = "19";

// select data that needs validation
$required   = array($name, $email);
$validEmail     = array($email);
$validNumber    = array($age);
$validAlpha     = array($name);

// check required fields
for ($i=0; $i<count($required); $i++) {
    if (strlen($required[$i]) == 0) {
        echo "Please fill out all required fields";
        $valid = false;
        break;
    }
}

// check for valid email field
for ($i=0; $i<count($validEmail); $i++) {
    if (preg_match('/^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/', $validEmail[$i])) {

    } else {
        echo '"' . $validEmail[$i] . '"' . ' is an invalid email address <br />';
        $valid = false;
    }
}

// check numeric fields
for ($i=0; $i<count($validNumber); $i++) {
    if (preg_match('/^[0-9 ]+$/', $validNumber[$i])) {

    } else {
        echo '"' . $validNumber[$i] . '"' . ' is an invalid number <br />';
        $valid = false;
    }
}

// check alpha
for ($i=0; $i<count($validAlpha); $i++) {
    if (preg_match('/^[a-zA-Z ]+$/', $validAlpha[$i])) {

    } else {
        echo '"' . $validAlpha[$i] . '"' . ' contains invalid characters. This field only accepts letters. <br />';
        $valid = false;
    }
}

// return "Your form was successfully sent"
if ($valid) {
    echo 'Your form was successfully sent. <br />Back to the site <form><input type="button" value="back" onclick="history.go(-1);return true;"></form>';
}

?>

Reducing repetitive code can commonly be avoided with:

  • loops (learn foreach instead of the manual for count)
  • functions
  • array rulesets

In your case you need to employ a better input variable handling, that keeps the names, and allows to filter like this:

$rules = array(
    "email" => FILTER_VALIDATE_EMAIL,
    "number1" => '/^[0-9 ]+$/',
    "alpha2" => '/^[a-zA-Z ]+$/',        
);

foreach ($rules as $varname => $verify) {
    if (is_int($verify) ? !filter_var($_REQUEST[$varname], $verify)
                        : !preg_match($verify, $_REQUEST[$varname]))
    {
        echo "The field '$varname' contains invalid whatevers...";
        $valid = false;
    }
}

With an extra indirection from the verification rules to the variable names you could also have nicer error messages, of course. But that's the basic approach here. Again, using some custom functions further helps readability and reduced code.

to validate emails (and some other fields) you can (must ?) use filter_var instead of regex, for example :

filter_var('bob@example.com', FILTER_VALIDATE_EMAIL)

will return TRUE.

here is a list of filters for validation http://www.php.net/manual/en/filter.filters.validate.php

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM