jQuery unobtrusive validation ignores “cancel” class on submit button if used in Ajax form

一世执手 提交于 2019-11-28 00:12:12

That's a known limitation of Microsoft's unobtrusive ajax script. You could modify it to fix the bug. So inside the jquery.unobtrusive-ajax.js script replace the following on line 144:

$(form).data(data_click, name ? [{ name: name, value: evt.target.value }] : []);

with:

$(form).data(data_click, name ? [{ name: name, value: evt.target.value, className: evt.target.className }] : []);

In addition we are passing the class name to the handler so that it can decide whether it should trigger client side validation or not. Currently it always triggers validation no matter which button was clicked. And now on line 154 we modify the following test:

if (!validate(this)) {

with:

if (clickInfo[0].className != 'cancel' && !validate(this)) {

so that client side validation is no longer triggered if a submit button with class name cancel was used to submit the form. Another possibility is to scrape the jquery.unobtrusive-ajax.js script and replace your Ajax.BeginForm with a standard Html.BeginForm that you could unobtrusively AJAXify using plain old jQuery.

FINALLY I figured out a solution that in itself is unobtrusive

    // restore behavior of .cancel from jquery validate to allow submit button 
    // to automatically bypass all jquery validation
    $(document).on('click', 'input[type=image].cancel,input[type=submit].cancel', function (evt)
    {
        // find parent form, cancel validation and submit it
        // cancelSubmit just prevents jQuery validation from kicking in
        $(this).closest('form').validate().cancelSubmit = true;
        $(this).closest('form').submit();
        return false;
    });

Note: If at first try it appears that this isn't working - make sure you're not roundtripping to the server and refreshing the page with errors. You'll have to bypass validation on the server side by some other means - this just allows the form to be submitted without having to mess around adding .ignore attributes to everything in your form.

(you may need to add button to the selector if you're using buttons)

if Unobtrusive validation is not required, disable it and do all your checking on the server side.

You could check value of Submit button on the server side and proceed based on that:

add name attribute to both of your submit inputs:

<input type="submit" value="Save" name="btnSubmit" />
<input type="submit" value="Save anyway" class="cancel" name="btnSubmit" />

Update your action to take string btnSubmit. You may just put it in your model if you have one.

[HttpPost]
public ActionResult Edit(string emailfield, string btnSubmit)
{
    switch (btnSubmit)
    {
        case "Save":
            if(ModelState.IsValid)
            {
                // Save email
            }
            break;
        case "Save anyway":
            // Save email
            return RedirectToAction("Success");
            break;
    }
    // ModelState is not valid
    // whatever logic to re display the view
    return View(model);
}

UPDATE

I understand that client validation simplifies the job, but if you cannot figure out what is wrong with Ajax (i'm not familiar with it's behavior when class="cancel" is slapped on an input), you could write a script that would validate an input on the un-focus on the server side:

$('input[type=text]').blur(function(){
    $.ajax({
        url: '/ControllerName/ValidateInput',
        data: { inputName: $(this).val() },
        success: function(data) {
            //if there is a validation error, display it
        },
        error: function(){
            alert('Error');
        }
    });
});

Now you need to create an action that will do the validation of an input:

public ActionResult ValidateInput(string inputName)
{
    bool isValid = true;
    string errorMessage = "";
    switch (inputName)
    {
        case "password"
            // do password validation
            if(!inputIsValid)
            {
                isValid = false;
                errorMessage = "password is invalid";
            }
            break;
        case "email"
            // do email validation
            if(!inputIsValid)
            {
                isValid = false;
                errorMessage = "email is invalid";
            }
            break;
    }
    return Json(new { inputIsValid = isValid, message = errorMessage });
}

It's a bit of a hassle, but as I said, could work if you do not figure out client validation.


UPDATE

Don't know why I didn't think of this first... rather than relying on class="cancel" you could do something like this:

Give your "anyway" submit input Id:

<input type="submit" value="Save anyway" class="cancel" name="btnSubmit" id="submitAyway" />

Then have a script like this:

$('#submitAyway').click(function(evt) {
    evt.preventDefault();
    $('form').submit();
});

I haven't tested this, but in theory, this should submit form without validating it. You probably still will need server side validation as I showed in my very first example.

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