Search code examples
javascriptjqueryjquery-validateunobtrusive-validation

Preventing form from being submitted with manual validation


I implemented some custom validation logic with JQuery and Unobtrusive validation with help of the following post:

Manually set unobtrusive validation error on a textbox

To save you time reading through that post here is the simple javascript that forces a validation message to be displayed if something fails:

On my textbox .blur():

var errorArray = {};
errorArray["Slug"] = 'Some error message for the Slug text box';
$('#SomeFormId').validate().showErrors(errorArray);

Works great.

My problem is while the failed validation message is displayed, when submit is clicked the form submits just fine.

How can I implement custom validation with code above and prevent the form from being submitted when the message is displayed ? I tired doing something like $('#SomeFormId').valid = false; but it didn't work.

Thank you.


Solution

  • Using $('#SomeFormId') will not work because when you do:

    $('#SomeFormId').valid = false;
    

    and then when you access it in your form submit handler again using (what I assume):

    var form = $('#SomeFormId');   // or $(this)
    if (form.valid) {
        //
    }
    

    You're essentially creating two different objects, even though they're referring to the same DOM element. So setting valid = true in one will not update it in the second.

    The code you gave is very barebones though, so I'm assuming that your validation is separate from your submit handler (since it's in blur anyway), so what you can do is utilize something like .data() or a flag (just make sure that it's in context).

    // on blur
    $('#SomeFormId').data('isvalid', false);    // invalid
    
    // on submit
    var isvalid = $('#SomeFormId').data('isvalid');
    if (!isvalid) {
        // invalid form
        ev.preventDefault();
    }
    

    EDIT

    The jQuery Event object

    When you bind a function as an event handler in jQuery, one of the things that jQuery does silently for you is it "creates" a normalized Event object for you. This will contain information about the event you can use in the handler, and also allows you to control the behavior of the event in some ways.

    // setting a submit event on my form
    //                                       |   whatever you put here 
    //                                       V   is the event object.
    $('#SomeFormId').on('submit', function (ev) {
    
        // preventing the default action
        // : in a form, this prevents the submit
        ev.preventDefault();
    });