Search code examples
jqueryvalidationhttp-postevent-bubbling

jQuery validation not stopping postback


I have a custom validator defined using jQuery that checks to ensure that the required fields are completed before HTTPPost takes place. My Scripts are as follows:

<script>
$(document).ready(function() {
    $('#ContentProperties').hide();
    $('#FileSubmit').hide();
});

$(function () {
    $("input:file").change(function () {
        var fileName = $(this).val();
        if(fileName != null)
            $('#FileSubmit').show();
            $('#ContentProperties').show();
            alert("File successfully chosen please enter required metadata below");
    });
});

$(document).ready(function () {
    $("#FileSubmit").click(function () {
        var name = document.getElementById("name").value;
        var author = document.getElementById("author").value;
        var description = document.getElementById("description").value;
        var uploadDate = document.getElementById("uploaddate").value;
        var expiryDate = document.getElementById("expirydate").value;
        var contentType = document.getElementById("contenttypeid").value;
        var alertString = "";

        if (name.length == 0) {
            alertString += "NAME: You must enter a name for your content!\n" 
        }

        if (author.length < 6) {
            alertString += "AUTHOR: You must enter at least 6 characters for author!\n"
        }

        if (description.length < 20) {
            alertString += "DESCRIPTION: You must enter a valid description of at least 20 characters !\n"
        }

        if (uploadDate.length < 8 || uploadDate.length > 10) {
            alertString += "UPLOAD DATE: Date must be entered in format 01/01/2013 or 1/1/2013\n"
        }

        if (expiryDate.length < 8 || expiryDate.length > 10) {
            alertString += "EXPIRY DATE: Date must be entered in format 01/01/2013 or 1/1/2013\n"
        }

        if (alertString.length > 0) {
            alert(alertString)
            event.cancelBubble = true;
            event.returnValue = false;
            event.preventDefault();
            event.stopPropagation();
            return false;
        }
    });
});

When I click on the submit button with the validated fields left blank it is correctly displaying the error messages but it is failing to stop the post. How can I do this when using jQuery? Previously I have used javascript only and I was able to stop bubbling using:

event.cancelBubble = true;
event.returnValue = false;
event.preventDefault();
event.stopPropagation();

Solution

  • You haven't defined event:

    $("#FileSubmit").click(function (event) {
    

    Though I usually use e as a convention:

    $("#FileSubmit").click(function (e) {
        e.preventDefault();
    });
    

    Side note: I would change this to attach the handler to the form submit, not the submit button click. You could submit the form by hitting enter, and it would skip your click handler.