我正在努力学习PHP。我想验证我的表格,但无法达到我想要的效果。
username
字段为空或不使用empty()
函数,我想验证它。但如果它是假的,请不要显示用户名。password
字段。我想要的是仅当两个字段都不为空时才显示username
和password
。这是我到目前为止所拥有的。
<!DOCTYPE html>
<html>
<head>
<title>Form Validation</title>
</head>
<body>
<?php
$username = $password = '';
$username_err = $password_err = '';
if (isset($_POST['submit']))
{
if (empty($_POST['username']))
{
$username_err = "Username is required<br>";
}
else {
$username = htmlspecialchars($_POST['username']);
if (!preg_match("/^[a-zA-Z ]*$/",$username))
{
$username_err = "Only letters are required<br>";
}
}
if (empty($_POST['password']))
{
$password_err = "Password is required<br>";
}
else {
$password = sha1($_POST['password']);
}
}
?>
<form id="form" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="post">
Enter your username:<input type="text" name="username" value="<?php echo $username; ?>">
<span><?php echo $username_err; ?></span>
Enter your password:<input type="password" name="password">
<span><?php echo $password_err; ?></span>
<input type="submit" name="submit" value="Submit">
</form>
<h2>Results</h2><br><br>
<?php echo $username, '<br>', $password, '<br>'; ?>
</body>
</html>