PHP按顺序显示错误消息并重新显示正确的字段 [英] PHP Show error messages in order and re-display correct fields

查看:56
本文介绍了PHP按顺序显示错误消息并重新显示正确的字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个电子邮件表单,该表单检查三个字段,名称,有效电子邮件和评论.但是现在它的设置方式是,由于名称和注释位于一个功能中,因此即使电子邮件无效,它也会首先检查名称和注释,我该如何重写它以便按顺序检查字段.另外,我想重新显示没有错误的字段,因此用户不必再次键入.请帮忙.谢谢

I have an email form that checks three fields, name, valid email and comments. But the way it's set up now, since name and comments are in one function it first checks name and comments even if email is not valid, how can I re-write it so it checks the fields in order. Also, I would like to re-display the fields that have no errors, so the user doesn't have to type again. Please help. Thanks

<?php
$myemail = "comments@myemail.com";
$yourname = check_input($_POST['yourname'], "Enter your name!");
$email = check_input($_POST['email']);
$phone = check_input($_POST['phone']);
$subject = check_input($_POST['subject']);
$comments = check_input($_POST['comments'], "Write your comments!");

if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/", $email))
  {
    show_error("Enter a valid E-mail address!");
  }

exit();

function check_input($data, $problem='')
 {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
if ($problem && strlen($data) == 0)
{
    show_error($problem);
}
return $data;
}

function show_error($myError)
{
?>
<!doctype html>
<html>
<body>
<form action="myform.php" method="post">
 <p style="color: red;"><b>Please correct the following error:</b><br />
 <?php echo $myError; ?></p>
 <p>Name: <input type="text" name="yourname" /></P>
 <P>Email: <input type="text" name="email" /></p>
 <P>Phone: <input type="text" name="phone" /></p><br />
 <P>Subject: <input type="text" style="width:75%;" name="subject" /></p>
 <p>Comments:<br />
 <textarea name="comments" rows="10" cols="50" style="width: 100%;"></textarea></p>
 <p><input type="submit" value="Submit"></p>
</form>
</body>
</html>
<?php
exit();
}
?>

推荐答案

首先,我建议您一次验证所有字段,并在表单上显示所有适当的错误消息.主要原因是,如果用户必须一次提交一次完整的表单,这可能会给用户带来糟糕的体验.我宁愿一次尝试更正我的电子邮件地址,密码,注释和选择,而不是一次固定一次只是为了揭示下一个错误是什么.

First off, I would suggest you validate ALL of the fields at once, and display all appropriate error messages on the form. The primary reason is that it can be bad user experience if they have to submit your form a whole bunch of times because they have to address one error at a time. I'd rather correct my email address, password, comments, and selection in one try instead of fixing one at a time just to reveal what the next error is.

也就是说,这里有一些有关验证表单的指针.通常,这就是我处理要完成的工作的方式.这假定您的表单HTML和表单处理器(PHP)一起在同一个文件中(这就是您现在拥有的文件).您可以将两者分开,但是这样做的方法可能会有所不同.

That said, here are some pointers on validating the form like you want. This is typically how I approach a form doing what you want to do. This assumes your form HTML and form processor (PHP) are together in the same file (which is what you have now). You can split the two, but the methods for doing that can be a bit different.

  • 具有一个功能或代码块,该功能或代码块可输出表格并了解您的错误消息,并且可以访问先前的表格输入(如果有).通常,它可以保留在函数之外,并且可以是PHP脚本中的最后代码块.
  • 为错误消息设置一个数组(例如$errors = array()).当该数组为空时,您将知道提交没有错误
  • 在输出表单之前,检查表单是否在脚本顶部附近提交.
  • 如果提交了表单,则一次验证每个字段,如果一个字段包含错误,则将错误消息添加到$errors数组(例如$errors['password'] = 'Passwords must be at least 8 characters long';)
  • 要使用以前的值重新填充表单输入,必须将输入的值存储在某个位置(可以只使用$_POST数组,也可以将$_POST值清理并分配给各个变量或数组) .
  • 完成所有处理后,您可以检查是否有任何错误,以决定此时是否可以处理表单,还是需要用户的新输入.
  • 为此,我通常会做类似if (sizeof($errors) > 0) { // show messages } else { // process form }
  • 的操作
  • 如果要重新显示表单,则只需向每个表单元素添加value=""属性,然后回显用户提交的值. 使用htmlspecialchars()或类似函数对输出进行转义非常重要
  • Have one function or code block that outputs the form and is aware of your error messages and has access to the previous form input (if any). Typically, this can be left outside of a function and can be the last block of code in your PHP script.
  • Set up an array for error messages (e.g. $errors = array()). When this array is empty, you know there were no errors with the submission
  • Check to see if the form was submitted near the top of your script before the form is output.
  • If the form was submitted, validate each field one at a time, if a field contained an error, add the error message to the $errors array (e.g. $errors['password'] = 'Passwords must be at least 8 characters long';)
  • To re-populate the form inputs with the previous values, you have to store the entered values somewhere (you can either just use the $_POST array, or sanitize and assign the $_POST values to individual variables or an array.
  • Once all the processing is done, you can check for any errors to decide whether the form can be processed at this point, or needs new input from the user.
  • To do this, I typically do something like if (sizeof($errors) > 0) { // show messages } else { // process form }
  • If you are re-displaying the form, you simply need to add a value="" attribute to each form element and echo the value that was submitted by the user. It is very important to escape the output using htmlspecialchars() or similar functions

在完成这些操作后,您可以对表格进行一些修改以实现此目的:

With those things in place, here is some re-work of your form to do that:

<?php
$myemail = "comments@myemail.com";
$errors  = array();
$values  = array();
$errmsg  = '';

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    foreach($_POST as $key => $value) {
        $values[$key] = trim(stripslashes($value)); // basic input filter
    }

    if (check_input($values['yourname']) == false) { 
        $errors['yourname'] = 'Enter your name!';
    }

    if (check_input($values['email']) == false) {
        $errors['email'] = 'Please enter your email address.';
    } else if (!preg_match('/([\w\-]+\@[\w\-]+\.[\w\-]+)/', $values['email'])) {
        $errors['email'] = 'Invalid email address format.';
    }

    if (check_input($values['comments']) == false) {
        $errors['comments'] = 'Write your comments!';
    }

    if (sizeof($errors) == 0) {
        // you can process your for here and redirect or show a success message
        $values = array(); // empty values array
        echo "Form was OK!  Good to process...<br />";
    } else {
        // one or more errors
        foreach($errors as $error) {
            $errmsg .= $error . '<br />';
        }
    }
}

function check_input($input) {
    if (strlen($input) == 0) {
        return false;
    } else {
        // TODO: other checks?

        return true;
    }
}
?>
<!doctype html>
<html>
<body>
<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post">
 <?php if ($errmsg != ''): ?>
 <p style="color: red;"><b>Please correct the following errors:</b><br />
 <?php echo $errmsg; ?>
 </p>
 <?php endif; ?>

 <p>Name: <input type="text" name="yourname" value="<?php echo htmlspecialchars(@$values['yourname']) ?>" /></P>
 <P>Email: <input type="text" name="email" value="<?php echo htmlspecialchars(@$values['email']) ?>" /></p>
 <P>Phone: <input type="text" name="phone" value="<?php echo htmlspecialchars(@$values['phone']) ?>"/></p><br />
 <P>Subject: <input type="text" style="width:75%;" name="subject" value="<?php echo htmlspecialchars(@$values['subject']) ?>" /></p>
 <p>Comments:<br />
 <textarea name="comments" rows="10" cols="50" style="width: 100%;"><?php echo htmlspecialchars(@$values['comments']) ?></textarea></p>
 <p><input type="submit" value="Submit"></p>
</form>
</body>
</html>

我有一个更高级的示例,您可以在此处看到可能还会给您一些指导.

I have a more advanced example which you can see here that may give you some guidance as well.

希望有帮助.

这篇关于PHP按顺序显示错误消息并重新显示正确的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆