Search code examples
c#asp.netasp.net-mvcasp.net-mvc-3

Enforcing a model's boolean value to be true using data annotations


Simple problem here (I think).

I have a form with a checkbox at the bottom where the user must agree to the terms and conditions. If the user doesn't check the box, I'd like an error message to be displayed in my validation summary along with the other form errors.

I added this to my view model:

[Required]
[Range(1, 1, ErrorMessage = "You must agree to the Terms and Conditions")]
public bool AgreeTerms { get; set; }

But that didn't work.

Is there an easy way to force a value to be true with data annotations?


Solution

  • using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.Threading.Tasks;
    using System.Web.Mvc;
    
    namespace Checked.Entitites
    {
        public class BooleanRequiredAttribute : ValidationAttribute, IClientValidatable
        {
            public override bool IsValid(object value)
            {
                return value != null && (bool)value == true;
            }
    
            public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
            {
                //return new ModelClientValidationRule[] { new ModelClientValidationRule() { ValidationType = "booleanrequired", ErrorMessage = this.ErrorMessage } };
                yield return new ModelClientValidationRule() 
                { 
                    ValidationType = "booleanrequired", 
                    ErrorMessage = this.ErrorMessageString 
                };
            }
        }
    }