I’m looking for a little help structuring a web form to include PHP validation and error messages placed in the correct place on the form if the submission is unsuccessful. I’ve just put together a simple form with some random validation rules just for proof of concept before I feed the actual form info and validation I require into the structure.
Here’s my code:-
<?php
if($_POST['name'] && $_POST['email']) {
$errors = array();
$name = $_POST['name'];
$email = $_POST['email'];
if (strlen($name) > 10) {
$errors['name'] = 'Name is too long';
}
if(empty($name) || empty($email)) {
$errors['required'] = 'All fields required';
}
}
if(empty($errors) && $_POST) {
echo 'Your form has been submitted';
} elseif ($errors || !$_POST) {
?>
<form name="form" action="index.php" method="post">
<?PHP if (isset($errors['required'])) { echo $errors['required'];} ?>
Name:<br>
<input type="text" name="name" value="<?php echo $name ?>"><?PHP if (isset($errors['name'])){ echo $errors['name']; } ?><br>
Email<br>
<input type="text" name="email"><br>
<input type="submit" name="submit" value="submit">
</form>
<?PHP }
?>
The result of which, is my form shows and submits, but the validation is kind of ignored. If any of the validation results in an error, rather than the errors displaying on the form, the page simply returns blank, no error messages or form. Can anyone please advise where i’m going wrong?
Any help would be greatly appreciated!
Thanks, Ben (If you hadn’t guessed im new to PHP and HTML!)
if($_POST['name'] && $_POST['email']) {will return false if one or both of the fields is/are left empty so the validation (which occurs inside the conditional) is never run.If the email address is provided and the name is longer than 10 characters the form shows with the relevant error (“Name is too long”)