-1

I want to prevent form submission when email or username is not available (not found in database) or when passwords don't match. (Password and "confirm password" don't match).

A similar question is asked here: JavaScript code to stop form submission

The suggestion was to use a function that returns a boolean value and use it to determine if form should bw submitted or not.

I tried to make something similar usimg ajax but I couldn't return value from Ajax in the function.

Here's the PHP code that helps with checking if email or username exists.:

    if (isset($_POST['username_check'])) {
    $username = $_POST['username'];
    $stmt = $db->prepare("SELECT count(*) as cntUser FROM Users WHERE username = :username");
    $stmt->bindValue(':username', $username, PDO::PARAM_STR);
    $stmt->execute();
    $count = $stmt->fetchColumn();
    if($count > 0){
        echo "taken";
    } else {
        echo 'not_taken';
    }
    exit();
}
if (isset($_POST['email_check'])) {
    $email = $_POST['email'];
    $stmt = $db->prepare("SELECT count(*) as cntUser FROM Users WHERE email = :email");
    $stmt->bindValue(':email', $email, PDO::PARAM_STR);
    $stmt->execute();
    $count = $stmt->fetchColumn();
    if($count > 0) {
        echo "taken";
    } else {
        echo 'not_taken';
    }
    exit();
}

Here's the HTML code with some javascript:

        <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Register User</title>
    </head>
    <script>
// This code prints red or blue text on whether passwords match or not and return a boolean value
        var check = function() {
            var pass1 = document.getElementById("password").value;
            var pass2 = document.getElementById("password2").value;
            if (pass1 != "" && pass2 != "") {
                if (pass1 === pass2) {
                    document.getElementById('message').style.color = 'green';
                    document.getElementById('message').innerHTML = 'matching';
                    return true;
                } else {
                    document.getElementById('message').style.color = 'red';
                    document.getElementById('message').innerHTML = 'not matching';
                    return false;
                }
            }
            else document.getElementById('message').innerHTML = '';
            return false;
        }

    //If both passwords don't match, it should be impossible to submit form
       function validate(){
            var pass1 = document.getElementById("password").value;
            var pass2 = document.getElementById("password2").value;
            return check();
        }
    </script>
    <body>
    <h1>Register user</h1>
    <form method="post" id="register_form" onsubmit="return validate();">
        <label>Username:</label>
        <div id="error_msg"></div>
        <div>
        <br><input type="text" name="username" value="" placeholder="User name" maxlength=30 required id="username" />
        <span></span>
        </div>
        <div>
        <br><label>First Name:</label>
        <br><input type="text" name="firstname" value="" placeholder="First name" maxlength=45 required id="firstname" />
        <br><label>Last name:</label>
        <br><input type="text" name="lastname" value="" placeholder="Last name" maxlength=45 required id="lastname" />
            <div>
        <br><label>Epost:</label>
        <br><input type="email" name="email" value="" placeholder="Email" maxlength=45 required id="email" />
            <span></span>
        </div>
        <div>
        <br><label>Password: </label>
        <br><input type="password" name="password"  required id="password" placeholder="Password" maxlength=60 value="" onkeyup='check();'>
        <br><label>Confirm password:</label>
        <br><input type="password" name="password2" required id="password2" placeholder="Confirm Password" maxlength=60 value="" onkeyup='check();'/>
            <span></span><span id='message'></span>
        <input type="hidden" value="{{ getMac("Register") }}" name="XSRFPreventionToken">
        <br><input type="submit" name="register" id="reg_btn" value="Register"></form>
    <script src="../jquery-3.5.0.js"></script>
    <script src="../script.js"></script>
    </body>
    </html>

Here's the JavaScript code on script.js:

$('document').ready(function(){
    var result = false;
    var username_state = false;
    var email_state = false;
    var password_state = false;

    $('#username').on('blur', function(){
        var username = $('#username').val();
        if (username == '') {
            username_state = false;
            return;
        }
        $.ajax({
            url: 'process.php',
            type: 'post',
            data: {
                'username_check' : 1,
                'username' : username,
            },
            success: function(response){
                if (response == 'taken' ) {
                    username_state = false;
                    $('#username').parent().removeClass();
                    $('#username').parent().addClass("form_error");
                    $('#username').siblings("span").text('Sorry... Username already taken');
                }else if (response == 'not_taken') {
                    username_state = true;
                    $('#username').parent().removeClass();
                    $('#username').parent().addClass("form_success");
                    $('#username').siblings("span").text('Username available');
                }
            }
        });
    });
    $('#email').on('blur', function(){
        var email = $('#email').val();
        if (email == '') {
            email_state = false;
            return;
        }
        $.ajax({
            url: 'process.php',
            type: 'post',
            data: {
                'email_check' : 1,
                'email' : email,
            },
            success: function(response){
                if (response == 'taken' ) {
                    email_state = false;
                    $('#email').parent().removeClass();
                    $('#email').parent().addClass("form_error");
                    $('#email').siblings("span").text('Sorry... Email already taken');
                }else if (response == 'not_taken') {
                    email_state = true;
                    $('#email').parent().removeClass();
                    $('#email').parent().addClass("form_success");
                    $('#email').siblings("span").text('Email available');
                }
            }
        });
    });

//Check if everything is OK and submit form
    $('#reg_btn').on('click', function(){
        var username = $('#username').val();
        var email = $('#email').val();
        var password = $('#password').val();
        if (username_state == false || email_state == false) {
            $('#error_msg').text('Fix the errors in the form first');
            $("#register_form").submit(function(e){
                e.preventDefault();
            });
        } else $("#register_form").submit(function(e){
            e.submit();
        });
    });
});

I can prevent login when passwords don't match. And I do get messages when email or username is not available. But I couldn't prevent form submission when email or username is not available. (When you submit it just give error message, since I have "PK" and "unique keys" in my database tables that prevents duplicates of email and username).

How do I prevent form submission if (username_state == false || email_state == false) ?

Coder88
  • 1,015
  • 3
  • 10
  • 23

1 Answers1

1

You should set the listener to the form itself, not to the button of submitting.

    $("#form_id_here").submit(function(e){
         if (condition){
            e.preventDefault();
         }
    });
Farhad
  • 742
  • 6
  • 22