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

后端 未结 12 1186
慢半拍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: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:

    /// 
    /// Validation attribute that demands that a  value must be true.
    /// 
    /// Thank you http://stackoverflow.com/a/22511718
    [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
    public class MustBeTrueAttribute : ValidationAttribute, IClientValidatable
    {
        /// 
        /// Initializes a new instance of the  class.
        /// 
        public MustBeTrueAttribute()
            : base(() => "The field {0} must be checked.")
        {
        }
    
        /// 
        /// Checks to see if the given object in  is true.
        /// 
        /// The value to check.
        /// true if the object is a  and true; otherwise false.
        public override bool IsValid(object value)
        {
            return (value as bool?).GetValueOrDefault();
        }
    
        /// 
        /// Returns client validation rules for  values that must be true.
        /// 
        /// The model metadata.
        /// The controller context.
        /// The client validation rules for this validator.
        public IEnumerable 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");
    

提交回复
热议问题