How to make unobtrusive client-side validation wor

2019-03-31 21:35发布

问题:

I'm trying to make use of the MVC Foolproof Validation framework (http://foolproof.codeplex.com/) but I'm having trouble with the ModelAwareValidationAttribute class.

When I add a custom validation attribute, it works fine for server-side model validation, but not on the client-side.

If I use one of the built-in attributes supplied by the framework, client-side unobtrusive validation works, so I know (or at least I think I know) that I have the correct javascript libraries loaded.

Has anyone out there created a custom validation attribute using this framework at does it work with client-side unobtrusive validation? If so, what did you do to make it work?

I'm using Asp.Net MVC 3, in case that matters.

回答1:

Base on the http://foolproof.codeplex.com/SourceControl/latest#Foolproof/Client Scripts/mvcfoolproof.unobtrusive.js you can add your custom client validation rules as the server side sibling.

What I did in the projects is to extend the foolproof base on that file.

Example code:

(function () {

jQuery.validator.addMethod("foo", function (value, element, params) {
    //validation code...
});

// code based on link
var setValidationValues = function (options, ruleName, value) {
    options.rules[ruleName] = value;
    if (options.message) {
        options.messages[ruleName] = options.message;
    }
};

var $Unob = $.validator.unobtrusive;

$Unob.adapters.add("foo", ["dependentproperty", "dependentvalue", ...(add more parameters if you want)], function (options) {
    var value = {
        dependentproperty: options.params.dependentproperty,
        dependentvalue: options.params.dependentvalue,
    };
    setValidationValues(options, "foo", value);
});
})();

I hope that help you!