我有一个简单的 php 验证表单,它正在工作中。如果您将该字段留空并单击提交,它会显示正确的错误消息。问题在于正则表达式。例如,如果货币字段无效,则不会显示正确的错误消息。单击提交时,它会重新加载页面并删除文本框中的所有值。为什么它不会显示正确的错误信息?
HTML 表单
<form action="" method="post" id="form">
<label for="tile">Title: <em>*</em></label>
<input type="text" name="title" id="title" value="<?php echo $form['title']; ?>"> <?php echo $error['title'] ?>
<label for="currency">Currency: <em>*</em></label>
<input type="text" name="currency" id="currency" value="<?php echo $form['currency']; ?>"> <?php echo $error['currency'] ?>
<input type="submit" name="submit" id="submit">
</form>
PHP 验证器
//variables
$error_open = "<label class='error'>";
$error_close = "</label>";
$valid_form = TRUE;
$redirect = "success.php";
$form_elements = array('title', 'currency');
$required = array('title', 'currency');
foreach ($required as $require)
{
$error[$require] = '';
}
if (isset($_POST['submit']))
{
//process form
//get form data
foreach ($form_elements as $element)
{
$form[$element] = htmlspecialchars($_POST[$element]);
}
//check form elements
//check required fields
if ($form['title'] == '')
{
$error['title'] = $error_open . "* This field is required" . $error_close;
$valid_form = FALSE;
}
if ($form['currency'] == '')
{
$error['currency'] = $error_open . "* This field is required" . $error_close;
$valid_form = FALSE;
}
//check formatting
if ($error['title'] == '' && !preg_match('/^([A-Za-z0-9_-]+)/', $form['title']))
{
$error['title'] = $error_open . "* Enter a valid descriptive title" . $error_close;
$valid_form = FALSE;
}
if ($error['currency'] == '' && !preg_match('/^\s*[+-]?(\d*\.\d\d)\s*$/', $form['currency']))
{
$error['currency'] = $error_open . " Enter a valid decimal number <br> * Do not include Dollar($) sign <br> * Example: (1.00)" . $error_close;
$valid_form = FALSE;
}
//check for bad data
if (contains_bad_str($form['title']) ||
contains_bad_str($form['currency']))
{
$valid_form = FALSE;
}
if (contains_bad_str($form['title']) ||
contains_bad_str($form['currency']))
{
$valid_form = FALSE;
}
//check if form is valid
if ($valid_form)
{
//redirect
header("Location: " . $redirect);
}
else
{
include('form.php');
}
}