开发者

How do I validate forms and present error messages using PHP?

Let's say we have this form:

<form action="submit.php" method="post">
Username: <input type="text" name="username" />
Passwor开发者_高级运维d: <input type="password" name="password" />
<input type="Submit" value="Login" />
</form>

How do I validate this form using submit.php, and how do I present an error message if it doesn't pass validation? With Javascript validation I would just change the innerHTML of some element to the error message, but this is not possible with PHP. As you can see I'm a total newbie, so please help me out.


In ugly form:

<?php

$errors = array();

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $username = $_POST['username'];
    $pw = $_POST['password'];

    if (empty($username)) {
       $errors[] = "Please enter your username";
    }
    if (empty($pw)) {
       $errors[] = "Please provide your password";
    }
    if (!canLogin($username, $pw)) {
       $errors[] = "Invalid login. Try again";
    }

    if (count($errors) == 0) {
       ... login is ok, go do something else
    }
}

# Display error conditions, if there are any
if (count($errors) > 0) {
    echo "<p>The following errors must be corrected:</p><ul><li>";
    echo implode("</li><li>", $errors);
    echo "</ul>";
}

?>

<form ...>
<input .... value="<?php echo htmlspecialchars($username) ?>" />
<input ...>
</form>


You could always have the form's action submit to itself (same PHP script) and perform your validation there and if it passes continue to another url. And then in your form write some conditionals to insert a CSS class to highlight the field thats in error or show a message.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜