简体   繁体   中英

PHP validating individual form fields then all of them

My simple php form validation script:

$email      = (isset($_POST['email'])) ? $_POST['email'] : '' ;
$password       = (isset($_POST['password'])) ? $_POST['password'] : '' ;
$fname      = (isset($_POST['fname'])) ? $_POST['fname'] : '' ;
$lname      = (isset($_POST['lname'])) ? $_POST['lname'] : '' ;

if (!empty($email) && !empty($password) && !empty($fname) && !empty($lname)) {
    $auth->createAccount($email, $password, $fname, $lname);
}

For some reason it doesn't look very good to me.

How can I check each form field to indicate which one is the one that needs filling out and then at the end check to make sure all fields are filled out before calling the createAccount() function.

Note: the createAccount() function sanitizes the input so there is no need to do this here.

Most common way to deal with this that I've seen is to create an array:

if (!$_POST['email']) {$errors[] = 'Email field is empty.';}
if (!$_POST['password']) {$errors[] = 'Password field is empty.';}
if (!$_POST['fname']) {$errors[] = 'First name field is empty.';}
if (!$_POST['lname']) {$errors[] = 'Last name field is empty.';}

And then loop through the errors to display them:

foreach ($errors as $error) {
    echo $error.'<br>';
}

Try this:

<?php
$form_names = array(
    'email' => 'e-mail', 
    'password' => 'password',
    'fname' => 'firstname',
    'lname' => 'lastname'
); //So that the user understands the errors better
$errors = array();
foreach ($_POST as $field=>$val) {
    if (empty($val)) {
        array_push($errors, 'Please fill out ' . $form_names[$field]);
    }
}
if (count($errors) == 0) {
    //No errors call the submit PHP function
}
else {
    $string = implode('<br/>', $errors);
    echo '<p style="color:red;">' . $string . '</p>';
}
?>

However, the setback is that form names should be appropriate to echo out to the user in an intelligible way. As some may require spaces, you can create an array for form names connected to their actual and use that value to echo out to the user via. $good_name = $form_names[$field]

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