Destramic Posted May 3, 2010 Share Posted May 3, 2010 im writing a form validation script and have come across a small problem. the problem im having is when set my own error message: $Form->Required_Field("name", "text", "please eneter your name)"); then after viewing the form and entering an email it will show up with 2 errors for the name field...if anyone can help please form_Validation.php <?php define("FORM_ERROR_REQUIRED_VALUE", "%s : Please enter a %s"); define("FORM_ERROR_REQUIRED_EMAIL", "%s : Please enter a valid E-mail Address. Format - name@example.co.uk."); class Form_Validation { public $Fields = array(); public $Error_Messages = array(); public $Errors = false; public function Required_Field($field_name, $field_type, $error_message = NULL) { $this->Fields[$field_name]['name'] = $field_name; $this->Fields[$field_name]['type'] = $field_type; $this->Fields[$field_name]['error_message'] = $error_message; } public function Validate_Form() { foreach ($this->Fields as $field) { $field_name = $field['name']; $field_type = $field['type']; $error_message = $field['error_message']; $field_value = $_POST[$field_name]; switch ($field_type) { case "text": if (empty($field_value)) { $default_error_message = sprintf(FORM_ERROR_REQUIRED_VALUE, $field_name, $field_name); } break; case "email": if (!$this->Email_Validation($field_value)) { $default_error_message = sprintf(FORM_ERROR_REQUIRED_EMAIL, $field_name); } break; } if ($error_message && $default_error_message) { $this->Set_Error_Message($error_message); } else { $this->Set_Error_Message($default_error_message); } } } public function Display_Errors() { foreach ($this->Error_Messages as $errors) { echo $errors . "<br />\n"; } } public function Set_Error_Message($error_message) { if (!in_array($error_message, $this->Error_Messages)) { $this->Error_Messages[]= $error_message; } } public function Email_Validation($email) { return eregi("^[_\.0-9a-zA-Z-]+@([0-9a-zA-Z][0-9a-zA-Z-]+\.)+[a-zA-Z]{2,6}$", $email); } } ?> form.php <?php require_once $_SERVER['DOCUMENT_ROOT'] . "\classes\Form_Validation.php"; $Form = new Form_Validation; $Form->Required_Field("name", "text", "please eneter your name)"); $Form->Required_Field("email", "email"); $Form->Validate_Form(); $Form->Display_Errors(); echo <<<HTML <form action="{$_SERVER['REQUEST_URI']}" name="test" method="POST"> <fieldset> <legend>Add League</legend> name: <input type="text" name="name" title="name"/><br /> email : <input type="text" name="email" title="email" /><br /> <input type="submit" value="Add League" title="Submit Form" /> <input type="reset" value="Reset" title="Reset Form" /> </fieldset> </form> HTML; ?> Quote Link to comment https://forums.phpfreaks.com/topic/200584-form-validation/ Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.