我在提交时有这个简单的表单,它会被重定向到submit.php
,如果有错误它会显示错误消息submit.php
。现在我想要将错误消息显示回表单页面。
<html>
<head>
<? require_once('lib.php'); ?>
</head>
<body>
<form name="my-form" id="my-form" method="post" action="submit.php">
Your name:
<input name="name" value="" size="30" maxlength="255" />
Your email:
<input name="email" value="" size="30" maxlength="255" />
Your favourite color:
<select name="fav_color">
<option value="">-select please-</option>
<option value="Black">Black</option>
<option value="White">White</option>
<option value="Blue">Blue</option>
<option value="Red">Red</option>
<option value="Yellow">Yellow</option>
</select>
Your comment:
<textarea name="comment" rows="6" cols="35"></textarea>
<input type="submit" value="Submit" />
</form>
</body>
</html>
<?php
require_once('lib.php');
function getErrors($postData,$rules){
$errors = array();
// validate each existing input
foreach($postData as $name => $value){
//if rule not found, skip loop iteration
if(!isset($rules[$name])){
continue;
}
//convert special characters to HTML entities
$fieldName = htmlspecialchars($name);
$rule = $rules[$name];
//check required values
if(isset($rule['required']) && $rule['required'] && !$value){
$errors[] = 'Field '.$fieldName.' is required.';
}
//check field's minimum length
if(isset($rule['minlength']) && strlen($value) < $rule['minlength']){
$errors[] = $fieldName.' should be at least '.$rule['minlength'].' characters length.';
}
//verify email address
if(isset($rule['email']) && $rule['email'] && !filter_var($value,FILTER_VALIDATE_EMAIL)){
$errors[] = $fieldName.' must be valid email address.';
}
$rules[$name]['found'] = true;
}
//check for missing inputs
foreach($rules as $name => $values){
if(!isset($values['found']) && isset($values['required']) && $values['required']){
$errors[] = 'Field '.htmlspecialchars($name).' is required.';
}
}
return $errors;
}
$errors = getErrors($_POST,$validation_rules);
if(!count($errors)){
echo 'Your form has no errors.';
}
else{
echo '<strong>Errors found in form:</strong><ul><li>';
echo join('</li><li>',$errors);
echo '</li></ul><p>Correct your errors and try again.</p>';
}
?>
由于此 php 代码在同一页面上显示错误消息。我想在form.php page
. 有没有人帮我这样做..