Question

I'm trying to get some client side validation working to prevent a form submission occurring if an object has no value. I've been plugging away at this for a while now but cannot get a satisfactory solution.

My form submission Js looks like this:

$(document).ready(function () {

    $('#localUsersDateTime').val(setLocalDateTime());

    $('#createentry').ajaxForm({
        beforeSubmit: checkTextObjHasValue($('#newentry'), 'You need to add some text.'),
        dataType: 'json',
        success: function (result) {
            $('#entries-list').prepend('<li>' + $('#newentry').val() + '</li>');
            $('#newentry').val('').blur();
        },
        error: function (xhr)
        {
            try {
                var json = $.parseJSON(xhr.responseText);
                alert(json.errorMessage);
            } catch (e) {
                alert('Oops, Something very bad has happened');
            }
        }
    });
    return false;
});

However when the page loads it runs my checkTextObjHasValue() specified in the beforeSubmit: function so that check needs to only execute on actual form submission.

function checkTextObjHasValue(obj, message) {

    if ($(obj).val() === '') {
        alert(message);
        return false;
    }

    return true;
}

How can I prevent this beforeSubmit: callback from being executed when just loading the page and only execute on actual form submission?

Was it helpful?

Solution

The beforeSubmit option expects a reference to a function. You were immediately calling a function. Try using this:

beforeSubmit: function () {
    return checkTextObjHasValue($('#newentry'), 'You need to add some text.');
},

The added return allows for the submission to cancel if false is actually returned (which is possible in checkTextObjHasValue under a certain condition).

Technically, it could've worked if you returned a function from checkTextObjHasValue, but I think this way is a little cleaner. And it lets you customize it in case you want to validate several fields.

UPDATE:

Like in the documentation for the plugin, you could take this approach:

beforeSubmit: beforeSubmitHandler,

And then define a function separately like this:

function beforeSubmitHandler() {
    return checkTextObjHasValue($('#newentry'), 'You need to add some text.');
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top