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

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

    My solution is this simple custom attribute for boolean values:

    public class BooleanAttribute : ValidationAttribute
    {
        public bool Value
        {
            get;
            set;
        }
    
        public override bool IsValid(object value)
        {
            return value != null && value is bool && (bool)value == Value;
        }
    }
    

    Then you can use it like this in your model:

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

    I got it by creating a custom attribute:

    public class BooleanRequiredAttribute : RequiredAttribute 
    {
        public override bool IsValid(object value)
        {
            return value != null && (bool) value;
        }
    }
    
    0 讨论(0)
  • 2020-12-04 10:16

    For people who are having trouble getting this working for validation on the client side (formerly me): make sure you have also

    1. Included <% Html.EnableClientValidation(); %> before the form in the view
    2. Used <%= Html.ValidationMessage or Html.ValidationMessageFor for the field
    3. Created a DataAnnotationsModelValidator which returns a rule with a custom validation type
    4. Registered the class deriving from DataAnnotationsModelValidator in the Global.Application_Start

    http://www.highoncoding.com/Articles/729_Creating_Custom_Client_Side_Validation_in_ASP_NET_MVC_2_0.aspx

    is a good tutorial on doing this, but misses step 4.

    0 讨论(0)
  • 2020-12-04 10:18
    [Compare("Remember", ErrorMessage = "You must accept the terms and conditions")]
    public bool Remember { get; set; }
    
    0 讨论(0)
  • 2020-12-04 10:22

    I would create a validator for both Server AND Client side. Using MVC and unobtrusive form validation, this can be achieved simply by doing the following:

    Firstly, create a class in your project to perform the server side validation like so:

    public class EnforceTrueAttribute : ValidationAttribute, IClientValidatable
    {
        public override bool IsValid(object value)
        {
            if (value == null) return false;
            if (value.GetType() != typeof(bool)) throw new InvalidOperationException("can only be used on boolean properties.");
            return (bool)value == true;
        }
    
        public override string FormatErrorMessage(string name)
        {
            return "The " + name + " field must be checked in order to continue.";
        }
    
        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            yield return new ModelClientValidationRule
            {
                ErrorMessage = String.IsNullOrEmpty(ErrorMessage) ? FormatErrorMessage(metadata.DisplayName) : ErrorMessage,
                ValidationType = "enforcetrue"
            };
        }
    }
    

    Following this, annotate the appropriate property in your model:

    [EnforceTrue(ErrorMessage=@"Error Message")]
    public bool ThisMustBeTrue{ get; set; }
    

    And Finally, enable client side validation by adding the following script to your View:

    <script type="text/javascript">
        jQuery.validator.addMethod("enforcetrue", function (value, element, param) {
            return element.checked;
        });
        jQuery.validator.unobtrusive.adapters.addBool("enforcetrue");
    </script>
    

    Note: We already created a method GetClientValidationRules which pushes our annotation to the view from our model.

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

    "Required" is the wrong validation, here. You want something akin to "Must have the value true," which is not the same as "Required". What about using something like:

    [RegularExpression("^true")]
    

    ?

    0 讨论(0)
提交回复
热议问题