4

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.

Phil
  • 157,677
  • 23
  • 242
  • 245
GP24
  • 867
  • 2
  • 13
  • 28
  • I think you ought to do some more digging to discover the source of this issue. I've been using unobtrusive validation in MVC for years, and have never run into the issue you're describing. – StriplingWarrior Apr 16 '14 at 03:10
  • have you used the remote attributes for ajax form submissions? This is 100% an issue, I have debugged and seen various questions on it, just hoping there has been some developments as it seems like a bit of a shocker. – GP24 Apr 16 '14 at 03:15
  • Yes, I have. I think I may understand what's going on here. The `[Remote]` attribute is supposed to cause client-side validation as soon as the value is changed, to provide immediate feedback to the user. However, the validation is asynchronous, and therefore non-blocking. As with *all* client-side validation, it's there to provide more immediate, consistent feedback to the user, and you're still expected to perform the same checks server-side. If you do, then the form post will produce the same result as if the `[Remote]` attribute had returned before submission. No hacks required. – StriplingWarrior Apr 16 '14 at 15:44
  • So you're saying reuse the validation methods to check values and only insert/update/whatever if valid, then the validation message will show anyway once it returns from the server? Do I understand correctly? Its actually not a bad idea – GP24 Apr 17 '14 at 06:22
  • Yes, I'll add this as an answer with some code in a moment. – StriplingWarrior Apr 17 '14 at 15:09

1 Answers1

3

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.

StriplingWarrior
  • 151,543
  • 27
  • 246
  • 315
  • 1
    Just wanted to say I finally got round to refactoring and using this method and it works perfectly, thank you very much for the example. – GP24 May 12 '14 at 01:37
  • This really doesn't answer the question. Isn't the whole point of client-side validation to keep the user from having to submit the entire form to the server for validation when it's just going to fail? It seems quite reasonable to want unobtrusive validation not to allow the form to be submitted until remote validation has completed, but this answer does not help with that problem. – John Washam Jul 15 '15 at 15:18
  • @JohnWasham: The point of client-side validation is to give the user feedback as quickly as possible. If I finish filling out the form and I hit "submit" before the remote validation round-trip returns, I'd rather have the form send the data immediately, rather than having the client hang in anticipation of finding out whether the server's likely to accept it. If remote validation fails, I'll find out just as quickly either way. But if it succeeds, then it'll succeed that much faster. – StriplingWarrior Jul 15 '15 at 15:39
  • @StriplingWarrior, I see what you mean. I guess the way I'm looking at it, the client-side remote validation I'm doing should return sub-second, or close to, so there's not really the idea of users waiting. It makes sense, in that scenario, to have the form be invalid until the remote validation returns with a yay or nay to the input, which is what the original question really was about. Been searching around and still haven't found an answer. – John Washam Jul 15 '15 at 20:38
  • @JohnWasham: The OP is specifically dealing with a slow remote validator that hadn't returned by the time the user tried to submit the form. In your case, it sounds like the validation is fast, but the form submission is slow. If the validation is that fast, how are users submitting the form before remote validation completes? Are you making the property `[Required]`, so users have to at least enter a value before they can submit the form? – StriplingWarrior Jul 15 '15 at 20:56
  • 1
    @StriplingWarrior, I may have just been thinking about it wrong. My form is only one element that someone else had rigged up to use remote validation to validate the input, so I was thinking inside that box. But like you said, it could take about the same amount of time to submit the form with potentially bad data than to wait for the remote validation to finish, _then_ submit the form. So now I'm tracking with your thinking. Thanks. – John Washam Jul 16 '15 at 00:44