Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 927
Steven Avatar asked Aug 08 '11 18:08

Steven


People also ask

How do you know if a Boolean value is true?

To check if a value is of boolean type, check if the value is equal to false or equal to true , e.g. if (variable === true || variable === false) . Boolean values can only be true and false , so if either condition is met, the value has a type of boolean. Copied!

How does data annotation help with model validation?

Data Annotations help us to define the rules to the model classes or properties for data validation and displaying suitable messages to end users.


1 Answers

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              };         }     } } 
like image 58
Ryan Gross Avatar answered Sep 28 '22 10:09

Ryan Gross