我正在处理一个 php 表单,我做了两部分,必填字段和可选字段。以下代码在“电子邮件”字段之外运行良好。我将电子邮件字段设置为可选字段,但不知何故它不能作为可选字段工作,它就像必填字段一样工作。如果有人可以粘贴代码并试一试?
非常感谢您的任何建议。
<?php
// Set required fields
$required_fields = array('phone');
$optional_fields = array('name','email');
// set error messages
$error_messages = array(
'name' => 'Please enter your name, letters only',
'phone' => 'Please enter a valid phone number',
'email' => 'Please enter a valid email address',
);
// Set form status
$form_complete = FALSE;
// configure validation array
$validation = array();
// check form submittal
if(!empty($_POST)) {
// Loop into required fields and make sure they match our needs
foreach($required_fields as $field) {
// the field has been submitted?
// if(!array_key_exists($field, $_POST)) array_push($validation, $field);
// check there is information in the field?
if($_POST[$field] == '') array_push($validation, $field);
// validate the phone number supplied
if($field == 'phone') if(!validate_phone_number($_POST[$field])) array_push($validation, $field);
}
//starts here for optional validation
foreach($optional_fields as $field){
if(!array_key_exists($field, $_POST)) array_push($validation, $field);
// validate the name if supplied
if($field == 'name') if(!validate_name($_POST[$field])) array_push($validation, $field);
// validate the email address supplied
if($field == 'email') if(!validate_email($_POST[$field])) array_push($validation, $field);
} // basic validation result
if(count($validation) == 0) {
$form_complete = TRUE;
}
}
//functions for validation different fields
function validate_name($phone = FALSE) {
return (!preg_match('/[^a-zA-Z ]/', $phone))? TRUE : FALSE;
}
function validate_email($email = FALSE) {
return (preg_match('/^[^@\s]+@([-a-z0-9]+\.)+[a-z]{2,}$/i', $email))? TRUE : FALSE;
}
function validate_phone_number($phone = FALSE) {
return (!preg_match('/\D/', $phone))? TRUE : FALSE;
}
?>
<?php if($form_complete === FALSE): ?>
<form id="form" name="form" method="post" action="">
<label for="name">Name:</label>
<input class="inter" type="text" name="name" id='name' value="<?php echo isset($_POST['name'])? $_POST['name'] : ''; ?>"/><?php if(in_array('name', $validation)): ?><span class="phperror"><?php echo $error_messages['name']; ?></span><?php endif; ?>
<p></p>
<label for="phone">Phone:</label>
<input type="text" name="phone" id='phone' value="<?php echo isset($_POST['phone'])? $_POST['phone'] : ''; ?>"/><?php if(in_array('phone', $validation)): ?><span class="phperror"><?php echo $error_messages['phone']; ?></span><?php endif; ?>
<p></p>
<label for="email">Email:</label>
<input type="text" name="email" id='email' value="<?php echo isset($_POST['email'])? $_POST['email'] : ''; ?>"/><?php if(in_array('email', $validation)): ?><span class="phperror"><?php echo $error_messages['email']; ?></span><?php endif; ?>
<p></p>
<input type="submit" value="Send" />
</form>
<?php else: ?>
<h2>Your message was sent</h2>
<?php endif; ?>