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.

  1. I want to validate theusername field if it's empty or not usingempty() function. But if it's false, do not display the username yet.
  2. Validate thepassword field if empty or not using the same function.
  3. What I want is to display theusername 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>
    

People are also looking for solutions to the problem: php - Call to undefined function recode_string() ubuntu

Source

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.

Ask a Question

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.

Similar questions

Find the answer in similar questions on our website.