PHP Form Validation Using empty() Function
Get the solution ↓↓↓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>
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: cannot use isset() on the result of an expression (you can use "null !== expression" instead)
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.