0
votes

Relates to: ASP.NET MVC 3 client-side validation with parameters

I built a custom validation attribute allowing me to check relative dates (ex. model value less than or equal to Today).

The validator correctly implements the GetClientValidationRules method and the HTML5 emitted in the view looks correct to me:

<div class="editor-label">
    <label for="Date">Date</label>
</div>
<div class="editor-field">
    <input class="text-box single-line" data-val="true" data-val-date="The field Date must be a date." data-val-relativedate="Date must be less than or equal to 12/04/2012" data-val-relativedate-referencedate="12/04/2012 00:00:00" data-val-relativedate-relativityoperator="lessThanOrEqual" data-val-required="The Date field is required." id="Date" name="Date" type="date" value="" />
    <span class="field-validation-valid" data-valmsg-for="Date" data-valmsg-replace="true"></span>
</div>

The next step was to define a custom jQuery Unobtrusive Validator adapter and method:

// Validation Method: Relative Date
// Note: method name value does NOT need to match the HTML5 metadata built by the server model annotation attribute.
$.validator.addMethod("validateRelativeDate", function (value, element, params) {
    // "element" is the actual HTML element we are validating, and is unneeded here.
    // "value" is the value of the HTML element
    var toValidate = DateUtilities.convert(value);
    // "params" is a JSON collection of those values provided by the adapter.
    var referenceDate = params["referencedate"];
    var relativityOperator = params["relativityoperator"];

    if (relativityOperator != "lessThan" && relativityOperator != "lessThanOrEqual" || relativityOperator != "greaterThan" && relativityOperator != "greaterThanOrEqual")
        return false; // "Invalid relativity operator (ex. '<', '<=', '>', or '>=').");

    var toReference = referenceDate == null ? new Date() : referenceDate;

    var relativity = DateUtilities.compare(toValidate, toReference);

    switch(relativityOperator) {
        case "lessThan":
            if (relativity >= 0) return false; //"Date must be lesser than " + toReference);
        break;
        case "lessThanOrEqual":
            if (relativity > 0) return false; //"Date must be less than or equal to " + toReference);
        break;
        case "greaterThan":
            if (relativity <= 0) return false; //"Date must be greater than " + toReference);
        break;
        case "greaterThanOrEqual":
            if (relativity < 0) return false; //"Date must be greater than or equal to " + toReference);
        break;
    }

    return true;

});

// note: adapter name must match HTML metadata built by the server model annotation attribute
$.validator.unobtrusive.adapters.add("relativedate", ["referencedate", "relativityoperator"], function (options) {
    options.rules["relativedate"] = options.params;
    options.messages["relativedate"] = options.message;
});

Symptom

The date validation is broken. Required seems to work fine. But whenever I type any value in this field the Date type validator triggers and produces the message "The field Date must be a date". This occurs for ANY date value entered.

Question

What is wrong with my validation rule that it (1) does not work, and (2) sabotages the Date type validation?

1

1 Answers

2
votes

As with most debugging experiences, the symptom had nothing to do with what was going on. Both the Required and Date Type validations were succeeding. The failure was caused in the adapter.

Explanation

Using browser script debuggers I found it failing on this line:

// jQuery.validate.js, line 530
result = $.validator.methods[method].call( this, val, element, rule.parameters );

This is where jQuery loops through the rules and their associated methods for validation.

method then was equal to "relativedate" (the metadata value spit out in HTML5) and thus the call property was throwing an exception. I named my method differently $.validator.addMethod("validateRelativeDate", /*...*/) and the documentation said it did not have to match this metadata value... so why was this happening?

It's the adapter. I knew the adapter name must be the same as the HTML5 metadata, which is the tight coupling between the two - thus "relativedate" seen below.

// note: adapter name must match HTML metadata built by the server model annotation attribute $.validator.unobtrusive.adapters.add("relativedate", ["referencedate", "relativityoperator"], function (options) { options.rules["relativedate"] = options.params; options.messages["relativedate"] = options.message; });

The two lines adding array values for rules and messages were the culprit. Apparenly these values need to be the name of the method used for validation, not the name of the adapter/metadata.

Solution

Changing these two lines to match the validation method name, solved everything:

options.rules["validateRelativeDate"] = options.params;
options.messages["validateRelativeDate"] = options.message;

Excuses, excuses...

All of the examples I researched and even the one I referenced, all of these values are equal so this detail was never discussed. But ultimately it means I was a bit of a lackwit programmer not to realize that this is the only way it "adapts" the HTML5 crap to the validation method.

Hopefully this helps someone or saves them time.