Jquery Unobtrusive validation lost after implementing onSubmit event

半腔热情 提交于 2019-12-12 02:59:58

问题


I'm using ASP.NET MVC. My validation works well until I attached an event to the form's onSubmit event.

This is how my form looks:

@using (Html.BeginForm("Recover", "Auth", FormMethod.Post, new { Id = "RecForm", onSubmit = "return Events.Submit(this,event)" }))
{
        @Html.TextBoxFor(model => model.Email)
        @Html.ValidationMessageFor(model => model.Email)
        <input type="submit" value="Recover" />
}

The Javascript (works fine, just put it here so you can check if something in this is causing the validation not to fire):

//Events
window.Events = (function () {

    // Baseline setup
    var Events = {};

    function disableAllChildren(el) {
        $(el).find(':input').attr('disabled', true);
    }
    function enableAllChildren(el) {
        $(el).find(':input').attr('disabled', false);
    }

    //Ajax submit
    Events.Submit = function (el, event) {
        event.preventDefault();
        //serialize the form before disabling the elements.
        var data = $(el).serialize();

        disableAllChildren(el);
        $(el).find('.success, .error').hide();
        $.ajax({
            url: el.action,
            type: 'POST',
            data: data,
            success: function (data) {
                //Stuff happens.
            }
        });
    };
    return Events;
})(this, this.document);

How do I get back my validations?


回答1:


What I do is to check if the form is valid before I submit it. See the below code :

$form = $("#myForm");

if (form.valid()) {

    form.validate();
    //other codes here

 }

If the form is valid, then post your data. If not, do nothing.




回答2:


There're more problems in your code than validation. Case is that disabled fields do not get posted to server. They do not participate in validation either. So, even if your code worked, you would get nothing posted to server side. Remove disableAllChildren(el); or recode it to not disable fields, but maybe make them readonly.

With this, they will get validated, but not surprisingly after the ajax submit. This is behavior you should not wish, so take a look at validate method. Especially you should be interested in part where it

Submits the form via Ajax when valid.

I believe that way validated form ajax submission can be done easier.

$(".selector").validate({
   submitHandler: function(form) {
    $(form).ajaxSubmit();
   }
})

Or, just add validation checking right before ajax submit



来源:https://stackoverflow.com/questions/7564991/jquery-unobtrusive-validation-lost-after-implementing-onsubmit-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!