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?
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!
Data Annotations help us to define the rules to the model classes or properties for data validation and displaying suitable messages to end users.
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 }; } } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With