Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6473301
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 25, 20262026-05-25T06:27:00+00:00 2026-05-25T06:27:00+00:00

Given the following viewmodel: public class SomeViewModel { public bool IsA { get; set;

  • 0

Given the following viewmodel:

public class SomeViewModel
{
  public bool IsA { get; set; }
  public bool IsB { get; set; }
  public bool IsC { get; set; } 
  //... other properties
}

I wish to create a custom attribute that validates at least one of the available properties are true. I envision being able to attach an attribute to a property and assign a group name like so:

public class SomeViewModel
{
  [RequireAtLeastOneOfGroup("Group1")]
  public bool IsA { get; set; }

  [RequireAtLeastOneOfGroup("Group1")]
  public bool IsB { get; set; }

  [RequireAtLeastOneOfGroup("Group1")]
  public bool IsC { get; set; } 

  //... other properties

  [RequireAtLeastOneOfGroup("Group2")]
  public bool IsY { get; set; }

  [RequireAtLeastOneOfGroup("Group2")]
  public bool IsZ { get; set; }
}

I would like to validate on the client-side prior to form submission as values in the form change which is why I prefer to avoid a class-level attribute if possible.

This would require both the server-side and client-side validation to locate all properties having identical group name values passed in as the parameter for the custom attribute. Is this possible? Any guidance is much appreciated.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-25T06:27:00+00:00Added an answer on May 25, 2026 at 6:27 am

    Here’s one way to proceed (there are other ways, I am just illustrating one that would match your view model as is):

    [AttributeUsage(AttributeTargets.Property)]
    public class RequireAtLeastOneOfGroupAttribute: ValidationAttribute, IClientValidatable
    {
        public RequireAtLeastOneOfGroupAttribute(string groupName)
        {
            ErrorMessage = string.Format("You must select at least one value from group \"{0}\"", groupName);
            GroupName = groupName;
        }
    
        public string GroupName { get; private set; }
    
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            foreach (var property in GetGroupProperties(validationContext.ObjectType))
            {
                var propertyValue = (bool)property.GetValue(validationContext.ObjectInstance, null);
                if (propertyValue)
                {
                    // at least one property is true in this group => the model is valid
                    return null;
                }
            }
            return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
        }
    
        private IEnumerable<PropertyInfo> GetGroupProperties(Type type)
        {
            return
                from property in type.GetProperties()
                where property.PropertyType == typeof(bool)
                let attributes = property.GetCustomAttributes(typeof(RequireAtLeastOneOfGroupAttribute), false).OfType<RequireAtLeastOneOfGroupAttribute>()
                where attributes.Count() > 0
                from attribute in attributes
                where attribute.GroupName == GroupName
                select property;
        }
    
        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            var groupProperties = GetGroupProperties(metadata.ContainerType).Select(p => p.Name);
            var rule = new ModelClientValidationRule
            {
                ErrorMessage = this.ErrorMessage
            };
            rule.ValidationType = string.Format("group", GroupName.ToLower());
            rule.ValidationParameters["propertynames"] = string.Join(",", groupProperties);
            yield return rule;
        }
    }
    

    Now, let’s define a controller:

    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            var model = new SomeViewModel();
            return View(model);        
        }
    
        [HttpPost]
        public ActionResult Index(SomeViewModel model)
        {
            return View(model);
        }
    }
    

    and a view:

    @model SomeViewModel
    
    <script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
    
    @using (Html.BeginForm())
    {
        @Html.EditorFor(x => x.IsA)
        @Html.ValidationMessageFor(x => x.IsA)
        <br/>
        @Html.EditorFor(x => x.IsB)<br/>
        @Html.EditorFor(x => x.IsC)<br/>
    
        @Html.EditorFor(x => x.IsY)
        @Html.ValidationMessageFor(x => x.IsY)
        <br/>
        @Html.EditorFor(x => x.IsZ)<br/>
        <input type="submit" value="OK" />
    }
    

    The last part that’s left would be to register adapters for the client side validation:

    jQuery.validator.unobtrusive.adapters.add(
        'group', 
        [ 'propertynames' ],
        function (options) {
            options.rules['group'] = options.params;
            options.messages['group'] = options.message;
        }
    );
    
    jQuery.validator.addMethod('group', function (value, element, params) {
        var properties = params.propertynames.split(',');
        var isValid = false;
        for (var i = 0; i < properties.length; i++) {
            var property = properties[i];
            if ($('#' + property).is(':checked')) {
                isValid = true;
                break;
            }
        }
        return isValid;
    }, '');
    

    Based on your specific requirements the code might be adapted.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Given the following source types: public class BaseViewModel { public string Prop1 { get;
Given the following code from a Microsoft example: public class EngineMeasurementCollection : Collection<EngineMeasurement> {
Given the following snippet, class Base { public: virtual void eval() const { std::cout<<Base
I have the following classes: public class ComplexType { public long? Code { get;
Given following HTML <select name="IBE1$IBE_NurFlug1$ddl_Abflughafen" id="IBE1_IBE_NurFlug1_ddl_Abflughafen" class="dropdownlist" style="width: 99%;"> <option value="Antalya;TR">Antalya</option> <option value="Berlin;DE">Berlin</option> <option
So as I understand it Given a view model public class MyViewModel{ public DateTime
Good day! I've the following ViewModel class I use for login form: using System.ComponentModel.DataAnnotations;
Given that I have the following widget (and a view attached to it): public
In the following code, the get action returns a betting card for a given
I've created the following view model: public class PropertyViewModel { public PropertyViewModel(Property property, IList<PropertyImage>

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.