RequireAtLeastNAttribute suggestion

Feb 1, 2011 at 3:37 PM
Edited Feb 1, 2011 at 5:10 PM

It would be useful to have the ability to require N fields to be filled from a group of selected fields on the model.  Adding an attribute such as the following to each field...

RequireAtLeastNAttribute(int N, string GroupName)

where N is > 0 and GroupName is unique across fields to support muliple groups.

Here is some JavaScript that may help:


    jQuery.validator.addMethod('required_group', function (value, element) {
        var selector = '#form0 .required_group';
        var valid = $(selector).filter(':filled').length;
        if (!$(element).data('reval')) {
            var fields = $(selector);
  'reval', true).valid();
  'reval', false);
        return valid;
    }, 'Please fill in at least one of these fields.');
    jQuery.validator.addClassRules('required_group', { 'required_group': true });


I attempted to created a custom validator however when I applied the same attribute to three different fields an exception was thrown.  I dropped the issue there and switched to using client only validation as above.  Best of luck.  Please post if you write a solution.

Feb 1, 2011 at 4:57 PM

Good afternoon could you post the code for your custom validator I was just looking to create something similar for my project?

Feb 1, 2011 at 5:13 PM

Here is a blog post detailing a complex validator that is dependent on more than one property in the model:

There is downloadable code at the bottom. And it should work exactly the same in MVC 3. 

Feb 1, 2011 at 5:40 PM
Ideally, the code would not be model aware and would show the error on all required fields. I don't believe this will do that without hard coding field names. Will it?