PHP Form Validation Using empty() Function
644
I'm trying to learn PHP. I wanted to validate the form I have but couldn't achieve what I want.
- I want to validate the
username
field if it's empty or not usingempty()
function. But if it's false, do not display the username yet. - Validate the
password
field if empty or not using the same function. What I want is to display the
username
andpassword
only if both fields are not empty. Here's what I have so far.<!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>