开发者

Jquery Unobtrusive validation lost after implementing onSubmit event

开发者 https://www.devze.com 2023-04-08 11:08 出处:网络
I\'m using ASP.NET MVC. My validation works well until I attached an event to the form\'s onSubmit event.

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 =开发者_JS百科> 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?


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号