How to handle Booleans/CheckBoxes in ASP.NET MVC 2 with DataAnnotations?

后端 未结 12 1137
慢半拍i
慢半拍i 2020-12-04 10:09

I\'ve got a view model like this:

public class SignUpViewModel
{
    [Required(ErrorMessage = \"Bitte lesen und akzeptieren Sie die AGB.\")]
    [DisplayName         


        
相关标签:
12条回答
  • 2020-12-04 10:31

    Found a more complete solution here (both server and client side validation):

    http://blog.degree.no/2012/03/validation-of-required-checkbox-in-asp-net-mvc/#comments

    0 讨论(0)
  • 2020-12-04 10:32

    My Solution is as follows (it's not much different to the answers already submitted, but I believe it's named better):

    /// <summary>
    /// Validation attribute that demands that a boolean value must be true.
    /// </summary>
    [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
    public class MustBeTrueAttribute : ValidationAttribute
    {
        public override bool IsValid(object value)
        {
            return value != null && value is bool && (bool)value;
        }
    }
    

    Then you can use it like this in your model:

    [MustBeTrue(ErrorMessage = "You must accept the terms and conditions")]
    [DisplayName("Accept terms and conditions")]
    public bool AcceptsTerms { get; set; }
    
    0 讨论(0)
  • 2020-12-04 10:32

    The proper way to do this is to check the type!

    [Range(typeof(bool), "true", "true", ErrorMessage = "You must or else!")]
    public bool AgreesWithTerms { get; set; }
    
    0 讨论(0)
  • 2020-12-04 10:34

    This might be a "hack" but you can use the built in Range attribute:

    [Display(Name = "Accepted Terms Of Service")]
    [Range(typeof(bool), "true", "true")]
    public bool Terms { get; set; }
    

    The only problem is the "warning" string will say "The FIELDNAME must be between True and true".

    0 讨论(0)
  • 2020-12-04 10:35

    It's enough to add [RegularExpression]:

    [DisplayName("I accept terms and conditions")]
    [RegularExpression("True", ErrorMessage = "You must accept the terms and conditions")]
    public bool AgreesWithTerms { get; set; }
    

    Note - "True" must start with capital T

    0 讨论(0)
  • 2020-12-04 10:38

    I'm just taking the best of the existing solutions and putting it together into a single answer that allows for both server side and client side validation.

    The to apply to model a properties to ensure a bool value must be true:

    /// <summary>
    /// Validation attribute that demands that a <see cref="bool"/> value must be true.
    /// </summary>
    /// <remarks>Thank you <c>http://stackoverflow.com/a/22511718</c></remarks>
    [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
    public class MustBeTrueAttribute : ValidationAttribute, IClientValidatable
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="MustBeTrueAttribute" /> class.
        /// </summary>
        public MustBeTrueAttribute()
            : base(() => "The field {0} must be checked.")
        {
        }
    
        /// <summary>
        /// Checks to see if the given object in <paramref name="value"/> is <c>true</c>.
        /// </summary>
        /// <param name="value">The value to check.</param>
        /// <returns><c>true</c> if the object is a <see cref="bool"/> and <c>true</c>; otherwise <c>false</c>.</returns>
        public override bool IsValid(object value)
        {
            return (value as bool?).GetValueOrDefault();
        }
    
        /// <summary>
        /// Returns client validation rules for <see cref="bool"/> values that must be true.
        /// </summary>
        /// <param name="metadata">The model metadata.</param>
        /// <param name="context">The controller context.</param>
        /// <returns>The client validation rules for this validator.</returns>
        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            if (metadata == null)
                throw new ArgumentNullException("metadata");
            if (context == null)
                throw new ArgumentNullException("context");
    
            yield return new ModelClientValidationRule
                {
                    ErrorMessage = FormatErrorMessage(metadata.DisplayName),
                    ValidationType = "mustbetrue",
                };
        }
    }
    

    The JavaScript to include to make use of unobtrusive validation.

    jQuery.validator.addMethod("mustbetrue", function (value, element) {
        return element.checked;
    });
    jQuery.validator.unobtrusive.adapters.addBool("mustbetrue");
    
    0 讨论(0)
提交回复
热议问题