jQuery unobtrusive validation ignores "cancel" class on submit button if used in Ajax form
P

3

6

I am trying to implement optional client side validation using

  • ASP.NET MVC 4,
  • unobtrusive jQuery validation,
  • unobtrusive ajax

This works fine

Following pictures show what I mean with optional client side validation: The only one field on my form is expected to contain email, so there is an email validator attached to it.

enter image description here

Now we click on save. Because our text "name@doamin" is not a valid email the validation summary gets displayed. Together with validation summary we are unhiding "Save anyway" button.

enter image description here

This second button is a normal submit button just having class="cancel". This instructs jQuery.validate.js script to skip validation when submitting using this button.

Here is the code snippet of the view:

@using (Html.BeginForm())
{
    <div>
        <input data-val="true" data-val-email="Uups!" name="emailfield" />
        <span class="field-validation-valid" data-valmsg-for="emailfield" data-valmsg-replace="false">*</span>
    </div>

    <input type="submit" value="Save" />
    @Html.ValidationSummary(false, "Still errors:")
    <div class="validation-summary-valid" data-valmsg-summary="true">
        <input type="submit" value="Save anyway" class="cancel" />
    </div>
}

These all works fine.

The problem

The second submit button - "Save anyway" stops working as expected if I switch over to Ajax form. It just behaves like the the normal one and prevents submit until validation succeeds.

Here is the code snippet of the "ajaxified" view:

@using (Ajax.BeginForm("Edit", new { id = "0" },
        new AjaxOptions
            {
                HttpMethod = "POST",
                InsertionMode = InsertionMode.Replace,
                UpdateTargetId = "ajaxSection",
            }))
{
    <div>
        <input data-val="true" data-val-email="Uups!" name="emailfield" />
        <span class="field-validation-valid" data-valmsg-for="emailfield" data-valmsg-replace="false">*</span>
    </div>

    <input type="submit" value="Save" />
    @Html.ValidationSummary(false, "Still errors:")
    <div class="validation-summary-valid" data-valmsg-summary="true">
        <input type="submit" value="Save anyway" class="cancel" name="saveAnyway" />
    </div>
}

I have debugged jQuery.validation.js to find out what is the difference, but failed.

Qustion

Any ideas to fix or workaround the problem and let the ajax form behave as intended are welcome.


Addendum

To have a client side validation is an absolute must. Server side validation is not an option. Aside from higher traffic (this sample is a simplification - the real form contains much more fields) and latency, there is one thing which server side validation would not do: client side validators highlight erroneous fields on lost focus. It means you have a feedback as soon as you tab to the next field.

Petrify answered 19/7, 2012 at 13:4 Comment(1)
You mentioned the class="cancel" makes the second submit button exempt from validation. How does this work, my question is unrelated to your actual question but I am looking for something similar.Fultz
M
11

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.

Moreland answered 26/7, 2012 at 6:7 Comment(5)
Hi @Darin thank you very much. It worked fine. I had only one issue: as you can see my submit had no name. In this case the clickInfo array has no elements and the check proposed in line 154 leads to script error. The fix would be to check it's length before. Also the name seems to be mandatory. Anyway after I added the name to my button everything worked fine.Petrify
One question: do you have some information (or know how to get it) about weather Microsoft is going to fix it soon? Otherwise if I go this way I'll be patching every new version again and again.Petrify
I have no information whether Microsoft intend to patch this, and yes, your submit button need to have a name for this to work.Moreland
This fixed my problem with two modifications. First to check if the className contains cancel rather than is only cancel to support multiple class names on the button. Second to check the clickInfo length before processing it to avoid script errors in special cases, as @achitaka-san reported. This changes line 154 to "if (clickInfo.length > 0 && clickInfo[0].className.indexOf('cancel') < 0 && !validate(this)) {". Thanks, yeah MS really should fix this.Dispirited
Please vote on this issue to get MSFT to fix it: aspnet.codeplex.com/workitem/7964Dispirited
L
7

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)

Lohse answered 1/7, 2013 at 9:56 Comment(1)
I know this is really old, but this helped me a lot. I had to use $(this).closest('form').validate().settings.rules = null; however to clear the rules for the jquery validation. The .cancelSubmit = true did not seem to work.Valona
V
-2

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.

Voluntary answered 25/7, 2012 at 17:53 Comment(4)
This won't work (to fix his specific issue) because his client side validation is what is being triggered, so the form data never goes to the server.Citizen
That could be an option in general, but client side validation is an absolute must. Aside from higher traffic (this sample is a simplification - the real form contains much more fields) and latency there is one thing which server side validation would not do: client side validators highlight erroneous fields on lost focus. It means you have a feedback as soon as you tab to the next field. I could probably made it clear in problem description. Thank you anyway.Petrify
then sounds like there is some javascript debugging needs to be done, which I'd rather not do :) Updated my answer with possible extension to the solutionVoluntary
Thanks @Dmitry I'll give it a try tomorrow. Yes it seems to be an issue of one of the java script libraries used here. That's why there is a bounty of +50 - for js debugging. :DPetrify

© 2022 - 2024 — McMap. All rights reserved.