2
\$\begingroup\$

I have created a registration form using jQuery. I am validating username and password using an AJAX request. The "submit" button is originally disabled and is only enabled when all three fields of username, email and password are filled and validated.

How and what can I improve in this code?

$(document).ready(function() {
    var usernameFlag = 1, emailFlag = 1, passwordFlag = 1;

    //event handler on input for username
    document.getElementById("reg_username").addEventListener("input", function() {
        var username = $("#reg_username").val();
        if(username !== null && username !== "") {
            usernameCheck(username).done(usernameCallback);
        }
        else {
            usernameFlag = 1;
            $("#tick_username").hide();
            $("#cross_username").hide();
            enableButton();
        }
    });

    //event handler on input for email
    document.getElementById("reg_email").addEventListener("input", function () {
        var email = $("#reg_email").val();
        if(email !== null && email !== "") {
            emailCheck(email).done(emailCallback);
        }
        else {
            emailFlag = 1;
            $("#tick_email").hide();
            $("#cross_email").hide();
            enableButton();
        }
    });

    //event handler on input for password
    document.getElementById("reg_password").addEventListener("input", function () {
        var password = $("#reg_password").val();
        if (password !== null && password !== "") {
            passwordFlag = 0;
            enableButton();
        }
        else {
            passwordFlag = 1;
            enableButton();
        }
    });

    function usernameCallback(response) {
        var usernameResponse = parseInt(response);
        usernameFlag = usernameResponse;
        if(usernameResponse === 1) {
            $("#tick_username").hide();
            $("#cross_username").fadeIn();
        }
        else {
            $("#cross_username").hide();
            $("#tick_username").fadeIn();
        }
        enableButton();
    }

    function emailCallback(response) {
        var emailResponse = parseInt(response);
        emailFlag = emailResponse;
        if(emailResponse === 1) {
            $("#tick_email").hide();
            $("#cross_email").fadeIn();
        }
        else {
            $("#cross_email").hide();
            $("#tick_email").fadeIn();
        }
        enableButton();
    }

    //ajax call to validate username
    function usernameCheck (username) {
        return $.ajax({
            type: "POST",
            url: "check_availability.php",
            data: "username="+username
        });
    }

    //ajax call to validate email
    function emailCheck (email) {
        return $.ajax({
            type: "POST",
            url: "check_availability.php",
            data: "email="+email
        });
    }


    //function to enable submit button
    function enableButton () {
        if (usernameFlag === 0 && emailFlag === 0 && passwordFlag === 0) {
            $("#register_btn").prop("disabled", false);
        }
        else {
            $("#register_btn").prop("disabled", true);
        }
    }

});

I am using three extra variables to keep track of the fields. The flags are updated if the user changes a value. After every change in input field, enableButton() checks the flags and enables the button if all of them have a value of 0.

\$\endgroup\$
4
\$\begingroup\$

Here is my take, dry some stuff.

You can glue each piece of code together to have a working script (I guess).


Keep track of your validations

var flags = {
    username: 1,
    password: 1,
    email: 1
};

jQuery seems to be included, so let's use it. The code of the reg_username and reg_email seems to be similair, so let's DRY it into a function named validates

$('#reg_username').on('input', function () {
    validates('username', $(this).val());
});


$('#reg_email').on('input', function () {
    validates('email', $(this).val());
});

The code of reg_password can be shorten a little.

$('#reg_password').on('input', function () {
    flags.password = !isBlank($(this).val())
    handleButton();
});

Here is the validates function

function validates (type, value) {
    if (!isBlank(value)) {
        remoteCheck(type, value).done(remoteCallback);
    } else {
        flags[type] = 1;
        hideFeedback(type);
        handleButton();
    }
}

You can dryify emailCheck and usernameCheck in a single function named remoteCheck by passing email or username in arguments.

function remoteCheck (type, value) {
    return $.ajax({
        type: 'POST',
        url: 'check_availability.php',
        data: type + '=' + value
    });
}

And here is the dryed callback for remoteCheck

function remoteCallback (type, value) {
    flags[type] = parseInt(response);
    handleFeedback(type, flags[type])
    handleButton();
}

The feedback can also be handled with a single function

function handleFeedback (type, flag) {
    hideFeedback(type);

    if (flag) {
        $('#cross_' + type).fadeIn();
    } else {
        $('#tick_' + type).fadeIn();
    }
}


function hideFeedback (type) {
    $('#tick_' + type).hide();
    $('#cross_' + type).hide();
}

To improve readability we put the flags checker in a separated function (and it now can be used elsewhere)

function handleButton () {
    $('#register_btn').prop('disabled', !isValid());
}


function isValid() {
    return flags.username === 0 && flags.email === 0 && flags.password === 0
}

You can create an utility function to check if a string is empty or null which is used many times in this script.

function isBlank (string) {
    return string === null || string === ''
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.