/ Published in: PHP
This is a good way to validate form input from PHP, in essence this could be a blue print for your forms.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
<?php // Quick function to loop through regexs and compare to what is in _POST // // $regs -> associative array of regular expressions // $ferrors -> error messages to display to the users asociative array function validatePost( $regs , $ferrors ) { foreach( $regs as $k => $v ) { { $errors[$k] = $ferrors[$k]; } } return $errors; } // has the post been submitted? { // yes it has been submitted so lets validate $regs['last_name'] = "/^[[:alpha:]\ -]+$/"; // require a alpha $regs['first_name'] = "/^[[:alpha:]\ -]+$/"; // require a alpha $regs['email'] = "/^..*\@..*$/"; // VERY simple email check // Use google to find better // Ok here are the error message to display when it is bad $ferrors['last_name'] = "Last name required"; $ferrors['first_name'] = "First name required"; $ferrors['email'] = "Email name required"; $errors = validatePost( $regs , $ferrors ); // Do we have errors? { // WE HAVE NO ERRORS DO SOMETHING // PUT IT INTO THE DATABASE, EMAIL, BOUNCE THE USER // TO A THANK YOU PAGE, ETC... } } ?> <!-- OK WE ARE IN HTML --> <!-- LETS MAKE THE FORM AND NOW YOU SEE HOW SIMPLE THIS IS I HOPE --> <form method="POST"> <p> <label>Last Name</label> <input type="text" name="last_name" value="<?= $_POST['last_name'] ?>" /> <span style="color: #FF0000;"><?= $errors['last_name'] ?></span> </p> <p> <label>First Name</label> <input type="text" name="first_name" value="<?= $_POST['first_name'] ?>" /> <span style="color: #FF0000;"><?= $errors['first_name'] ?></span> </p> <p> <label>Email</label> <input type="text" name="email" value="<?= $_POST['email'] ?>" /> <span style="color: #FF0000;"><?= $errors['email'] ?></span> </p> <p> <input type="submit" name="subby" value="GO" /> </p> </form>
URL: http://www.goingson.be/2009/05/my-super-awesome-php-functions-part-v.html