client-side validation in custom validation attribute - asp.net mvc 4

后端 未结 2 1545
陌清茗
陌清茗 2020-11-28 06:00

I have followed some articles and tutorials over the internet in order to create a custom validation attribute that also supports client-side validation in an asp.net mvc 4

相关标签:
2条回答
  • 2020-11-28 06:43

    Take a look at this: http://thewayofcode.wordpress.com/tag/custom-unobtrusive-validation/

    Using this tutorial I got my custom validation code running with no problem. The only difference I can spot in your code is the way you created the $.validator.unobtrusive.adapters.add function. The parameters are a little bit different but, maybe, the problem is just that you have not defined the rule part of your adapter.

    Try using something like this:

    $.validator.unobtrusive.adapters.add("requiredif", ["requiredif"], function (options) {
        options.rules["requiredif"] = "#" + options.params.requiredif;
        options.messages["requiredif"] = options.message;
    });
    

    or this

    $.validator.unobtrusive.adapters.add("requiredif", function (options) {
        options.rules["requiredif"] = "#" + options.element.name.replace('.', '_'); // mvc html helpers
        options.messages["requiredif"] = options.message;
    });
    

    About the rule (taken from the link):

    The jQuery rules array for this HTML element. The adapter is expected to add item(s) to this rules array for the specific jQuery Validate validators that it wants to attach. The name is the name of the jQuery Validate rule, and the value is the parameter values for the jQuery Validate rule.

    0 讨论(0)
  • 2020-11-28 06:47

    It's worth noting that the [RequiredIf] attribute needs to be added to the second form field in the view model in order for client validation to work.

    0 讨论(0)
提交回复
热议问题