When validating a form, most of the time the emphasis is on mandatory fields. You can check if they contain values in two ways:
It is very important that you combine both techniques. You always have to check for a field's existence using isset() to avoid error messages when trying to access array values that do not exist. But you always have to check whether there is something within the field apart from whitespace because text fields are always submitted. In addition, when empty, isset() always returns true independent of the field's value. Validating Mandatory Fields (mandatory.php; excerpt)<?php if (isset($_POST['Submit']) && isset($_POST['textfieldname']) && trim($_POST['textfieldname']) != '') { echo '<h1>Thank you for filling out this form!</h1>'; } else { ?> <form method="post" action=" <?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>"> <input type="text" name="textfieldname" value="<?php echo (isset($_POST['textfieldname'])) ? htmlspecialchars($_POST['textfieldname']) : ''; ?>" /> <input type="submit" name="Submit" /> </form> <?php } ?>
|