GP24
GP24

Reputation: 877

ASP.NET-MVC jQuery unobtrusive remote validation returns false positives

I am back on a project I last worked on 9 months ago, looking at some code we wrote and hoping there is now a better way to do this...

Though initially very impressed with jQuery's unobtrusive validation, we ended up having to put together the hack below (partly based on a blog post I can't put my hands on right now) to deal with remote validation. The problem being that where the server-side validation process was slow - typically anything involving a DB call - the validator would not wait for the response from the validation method and would act as though it had passed back a positive.

The hack is to basically keep checking if the validator has any pending requests and not carry on until it has none, when you can be sure of a true validation result:

function SaveChangePassword() {

// Find form, fire validation
var $form = $("#btnSave").closest("form");

if ($form.valid()) {
//Do nothing - just firing validation
}

// Calls method every 30 milliseconds until remote validation is complete
var interval = setInterval(saveWhenValidationComplete, 30);

// Check if validation pending, save and clear interval if not
function saveWhenValidationComplete() {

    // Find form validator, check if validation pending - save once remote validation is finished
    var validator = $form.data("validator");
    if (validator.pendingRequest === 0) {

        clearInterval(interval);

        //Force validation to present to user (this will not retrigger remote validation)
        if ($form.valid()) {

            var closeButton = "<br/><input type='button' value='OK' style='font-size:small; font-weight:bold; float:right;' onclick=\"$('#changePasswordDialog').dialog('close');\" class='greenbutton' />";
            // If form is valid then submit
            $.ajax(
                {
                    type: "POST",
                    url: "/Account/SavePassword",
                    data: $form.serialize(),
                    success: function (result) {
                        var successMessage = "<div style='text-align:center; margin-top: 10px;'>" + result + "<div>";
                        $("#changePasswordDialog").html(successMessage + closeButton);
                            },
                    error: function (jqXhr, textStatus, errorThrown) {
                        // Populate dialog with error message and button
                        var errorMessage = "<div style='text-align:center'>Error '" + jqXhr.status + "' (Status: '" + textStatus + "', errorThrown: '" + errorThrown + "')<div>";
                        $("#changePasswordDialog").html(errorMessage + closeButton);
                    }
                });

        }

        // Else validation will show
    }

    // Else don't save yet, wait another 30 miliseconds while validation runs
};

// Prevent default and stop event propagation
return false;
}

I am hoping that in the last 9 months there have been some developments and this is no longer necessary! Any ideas welcome, let me know if i can provide any further detail.

Upvotes: 4

Views: 3664

Answers (1)

StriplingWarrior
StriplingWarrior

Reputation: 156479

While you can provide client-side validation is provided as a nicety to your users, you should always (always!) re-validate on the server. It's really easy for users to disable javascript or otherwise fake an invalid POST to your controller action, and if you don't check things server-side you're creating an opportunity for users to corrupt the data in your system.

Fortunately, most validation in ASP.NET MVC is pretty much done for you. If your controller action looks like this:

public ActionResult SaveSomething(Something thing)
{
    if(!ModelState.IsValid)
    {
        return View("EditSomething", thing);
    }
    // otherwise, save something...
}

... then you're going to catch issues where users provided values that can't bind to your data properties, as well as the things validated by properties like [Required] and [StringLength(x)]. However, some forms of validation aren't automatically checked for you. [Remote] is one of these.

If you have a [Remote] attribute that points to a controller action like this:

public ActionResult CheckThingCodeValidity(string code)
{
    return Json(_thingCodeChecker.ThingCodeWorks(code), JsonRequestBehavior.AllowGet);
}

... then you should also have something like this in your submit action:

public ActionResult SaveSomething(Something thing)
{
    if(!_thingCodeChecker.ThingCodeWorks(thing.Code))
    {
        ModelState.AddModelError("Code", "This code is not valid.");
    }
    if(!ModelState.IsValid)
    {
        return View("EditSomething", thing);
    }
    // otherwise, save something...
}

That way, your standard server-side validation technique works to send the view back to the user, and gives them an error message on that property to indicate what they need to fix.

If you are doing this, then you don't have to worry about whether an asynchronous validation check is still underway when the form gets submitted. And it doesn't matter if your client-side validation fails generally, either through a defect, a network issue, or malicious user intervention. You'll still be preventing them from submitting something invalid, and they'll still get a nice view telling them why their submission was invalid.

Upvotes: 3

Related Questions