0

I have a problem with jquery ajax call on form submission. As I don't want my page to be refreshed when submitting a form, I do e.preventDefault()

Unfortunately this causes all the client side model data annotation validation not to be displayed. It is very important to me to display all the model validation at a client side.

Does anyone know a way of doing so? If I prevented some default behavior, how do I turn on the validation? Any help would be appreciated

$(function () {
    var form = $('#basicForm');
    form.on('submit', function (e) {
        e.preventDefault();

        $.ajax({
            cache: false,
            async: true,
            type: "POST",
            url: form.action,
            data: form.serialize(),
            success: function (result) {
                // for testing
                alert("success");
            }
        });
    });
});
tereško
  • 58,060
  • 25
  • 98
  • 150
Grentley
  • 315
  • 3
  • 6
  • 19

1 Answers1

0

Try adding form.validate():

$(function () {
    var form = $('#basicForm');
    form.on('submit', function (e) {
        e.preventDefault();
        form.validate();

        $.ajax({
            cache: false,
            async: true,
            type: "POST",
            url: form.action,
            data: form.serialize(),
            success: function (result) {
                // for testing
                alert("success");
            }
        });
    });
});
Amy Barrett
  • 564
  • 3
  • 14
  • 27
  • Unfortunately form.validate() is undefined – Grentley Mar 06 '16 at 11:11
  • $.validator.unobtrusive is undefined as well, but jquery.validate.js and jquery.validate.unobtrusive.js are being loaded without problems. When I remove the e.preventDefault(), validation works fine – Grentley Mar 06 '16 at 11:16
  • Ok, I've managed to have it defined. Though, the form.validate() returns number of properties, but it doesn't display them on the form as errors. – Grentley Mar 06 '16 at 11:27
  • Try form.valid() instead. I think .validate() might literally just validate the form, whereas .valid() does the highlighting etc. – Amy Barrett Mar 06 '16 at 11:45
  • form.valid() returns info whether the model is valid (true/false), so it doesn't highlight any errors – Grentley Mar 06 '16 at 11:49
  • Please could you post more of your code? I often use .valid() on input elements to do validation, so it should work. – Amy Barrett Mar 06 '16 at 11:52