tag print ''; } function display_form($defaults) { global $subject_options; ?>
} ///////////////////////////// WEEK 3 ASSIGNMENT /////////////////////////////// /* supply code to enforce the following validation rules: -- email field must look like an email address -- email field must be non-empty -- optional phone field, if not empty, must contain exactly 10 digits -- comments field must be non-empty -- comments field must not exceed 3000 characters length -- subject field must be non-empty -- subject field must be a member of your array $subject_options */ ///////////////////////////// A POSSIBLE SOLUTION /////////////////////////////// function validate_form($data) { $errors = array(); foreach ($data as $key => $value ) { $data[$key] = trim($value); } if (empty($data['email'])) { $errors[] = "Email address is required"; } elseif (! preg_match( '/^[^@\s]+@([-a-z0-9]+\.)+[a-z]{2,}$/i',$data['email'])) { $errors[] = 'Email address appears to be invalid'; } if (empty($data['comments'])) { $errors[] = 'The comments field is required'; } if (strlen($data['comments']) > 3000 ) { $errors[] = 'The comments field exceeds the maximum length'; } if (!empty($data['phone']) && 10 != strlen(preg_replace('/\D/','',$data['phone']))) { $errors[] = 'Your phone number must contain 10 digits.'; } if (empty($data['subject'])) { $errors[] = 'Subject field is required'; } if (! array_key_exists($data['subject'],$GLOBALS['subject_options'])) { $errors[] = 'Invalid subject field'; } return $errors; } function process($data) { echo "Thank you for your submission. Your comments are genuinely appreciated.
"; } // end function definitions /////////////////////////// // begin form-handling logic /////////////////////////// $subject_options = array(''=>'[select one]','rant'=>'rant','praise'=>'praise','question'=>'question'); if ($_POST) { $errors = validate_form($_POST); if ($errors) { echo "Sorry, we are unable to process your submission because:
Please correct your form below and re-submit it
"; display_form($_POST); } else { process($_POST); } } else { $defaults = array('subject'=>'','comments'=>'','phone'=>'','email'=>''); display_form($defaults); } ?>