0

I am having a code that will check if the username is available in the database, the code can show an error message that the email is already exists but when I press the submit button it will insert the username in the database even if the username is already exists.

here is my code:

function validateForm(){
<script>
$(document).ready(function () {
    $("#Name").change(function () {
        var username = $("#Name").val();
        var msg = $("#msg");
        if (username.length > 2) {
            $("#msg").html('Checking availability');
            $.ajax({
                type: "POST",
                url: "check_availability.php",
                data: "Name=" + username,
                success: function (messagess) {
                    $("#msg").ajaxComplete(function (event, request) {
                        if (messagess.indexOf('OK') > 0) {
                            $("#Name").removeClass("exists");
                            $("#Name").addClass("avail");
                            msg.html('the user name is available</font>');
                        } else {
                            $("#Name").removeClass("avail");
                            $("#Name").addClass("exists");
                            msg.html('the user name is already exists');
                        }
                    });
                }
            });
        }
    });
});
}
</script>
</head>
<body>

<form action="" method="post" name="form" onsubmit="return validateForm()">    
User Email:&nbsp;
<input type="text" name="Name" id="Name" value="" />
<span id="msg"></span>
</form>
</body>
</html>
2
  • 1
    Always check server side as well. Even if JavaScript validation is used, it is trivially easy to bypass that. On the server side send an error if there user-name is already in use. Never just rely on data from the client as being validated already. Commented Jul 28, 2013 at 16:13
  • Also, please use our search feature. See how to disable submit button with jquery Commented Jul 28, 2013 at 16:16

1 Answer 1

1

You'll wanna use .attr('disabled', 'disabled') on the the element you want to disable, if the check returns that the username already exists. And to remove the disabling you'll use .removeAttr('disabled').

And just a recommendation, if you havn't already throw in a fallback php validation check that way if javascript is disabled there is still validation in place.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.