How would you validate a checkbox in ASP.Net MVC 2?

前端 未结 4 1628
庸人自扰
庸人自扰 2021-01-05 03:09

Using MVC2, I have a simple ViewModel that contains a bool field that is rendered on the view as a checkbox. I would like to validate that the user checked the box. The [R

相关标签:
4条回答
  • 2021-01-05 03:47

    I usually use:

    [RegularExpression("true")]
    
    0 讨论(0)
  • 2021-01-05 03:50

    I too am looking for a way to have the model binder correctly handle check boxes with Boolean values. In the mean time I'm using this in the Actions:

    Object.Property = !String.IsNullOrEmpty(Request.Form["NAME"]);
    

    Maybe this will be of some use to you.

    0 讨论(0)
  • 2021-01-05 03:53

    If you didn't want to create your own custom validator and still wanted to use existing attributes in the model you could use:

    [Range(typeof(bool), "true", "true", ErrorMessage="You must accept the terms and conditions.")]
    

    This ensures that the range of the boolean value is between true and true. However, whilst this method will work, I would still prefer to use a custom validator in this scenario. I just thought i'd mention this as an alternative option.

    0 讨论(0)
  • 2021-01-05 04:08

    a custom validator is the way to go. I'll post my code which I used to validate that the user accepts the terms ...

    public class BooleanRequiredToBeTrueAttribute : RequiredAttribute
    {
        public override bool IsValid(object value)
        {
            return value != null && (bool)value;
        }
    }
    
    0 讨论(0)
提交回复
热议问题