Home > front end >  How to submit only when 2 text fields match?
How to submit only when 2 text fields match?

Time:08-22

I am implementing this code: https://www.geeksforgeeks.org/password-matching-using-javascript/

I want the submit action to happen ONLY when both passwords are matching. But there is a problem If I leave the fields empty or passwords don't match. It executes the action submit anyway, so how can I force It to ONLY execute it if both inputs match and are not empty?

Here is the code:

<!DOCTYPE html>
<html>
    <head>
        <script>
        
            // Function to check Whether both passwords
            // is same or not.
            function checkPassword(form) {
                password1 = form.password1.value;
                password2 = form.password2.value;

                // If password not entered
                if (password1 == '')
                    alert ("Please enter Password");
                    
                // If confirm password not entered
                else if (password2 == '')
                    alert ("Please enter confirm password");
                    
                // If Not same return False.    
                else if (password1 != password2) {
                    alert ("\nPassword did not match: Please try again...")
                    return false;
                }

                // If same return True.
                else{
                    alert("Password Match: Welcome to GeeksforGeeks!")
                    return true;
                }
            }
        </script>
    </head>
    <body>
        <form onSubmit = "return checkPassword(this)" action="success.php" method="POST">
        <table border = 1 align = "center">
            <tr>
                <!-- Enter Password. -->
                <td>Password:</td>
                <td><input type = password name = password1></td>
            </tr>
            <tr>
                <!-- To Confirm Password. -->
                <td>Confirm Password:</td>
                <td><input type = password name = password2></td>
            </tr>
            <tr>
                <td colspan = 2 align = right>
                <input type = submit value = "Submit"></td>
            </tr>
        </table>
        </form>
    </body>
</html>

The success.php has just this

<?php
    echo("SUCCESS");
?>

CodePudding user response:

This is what you want to write

if (password == '') {
    alert ("Please enter the Password");
    return false;    
     }
else (password == '') {
     alert ("Please enter confirm the password");
      return false;
 }

CodePudding user response:

You need to return false if one of the passwords is empty

// If password not entered
if (password1 == '') {
    alert ("Please enter Password");
    return false;    
}

// If confirm password not entered
if (password2 == '') {
    alert ("Please enter confirm password");
    return false;
}
  • Related