[Solved] PHP Simple Form Validation


You have the following in your code:

$name = $_POST['$name'];
$email = $_POST['$email'];
$dob = $_POST['$dob'];

You’re basically trying to access undefined indexes. Remove the extra $ from the key names:

$name = $_POST['name'];
$email = $_POST['email'];
$dob = $_POST['dob'];

Then, further below, you have some conditions like this:

if(condition == true) {
    continue;
} else {
    // do something
}

It’s actually not necessary, and you could change it to:

if(!condition) {
    // do something
}

Also, it’s better to push the error messages into an array ($errors) and then loop through it and display the error messages. It might help organize your code a bit better.

Here’s how the modified code looks like:

if(!empty($_POST)) {
    $name = $_POST['name'];
    $email = $_POST['email'];
    $dob = $_POST['dob'];

    $namelen = strlen($name);
    $emaillen = strlen($email);
    $max = 255;
    $minname = 2;
    $minemail = 3;

    if($namelen < $minname){
        $errors[] = "name must be at least 2 characters";
    } elseif($namelen > $max){
        $errors[] = "name must be less than 255 characters";
    }

    if($emaillen < $minemail){
        $errors[] = "email must be at least 3 characters";
    } elseif($emaillen > $max){
        $errors[] = "email must be less than 255 characters";
    }

    if(empty($name)){
        $errors[] = "name is required";
    }

    if(empty($email)){
        $errors[] = "email cannot be left empty";
    }

    if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
        $errors[] = "invalid email";
    }

    echo "<ul>";
    foreach ($errors as $error) {
        echo "<li>$error</li>";
    }
    echo "</ul>";

}

It could still be improved, but however, this should get you started!

0

solved PHP Simple Form Validation