2

In my code first model I have the following.

public class Agreement
{
    [Key]
    [ForeignKey("AppRegistration")]
    public int AppRegistrationId { get; set; }
    [Required]
    [Display(Name = "I agree to Participation Agreement")]
    [NotMapped]
    public bool IsAgreementChecked { get; set; }
    public DateTime DateAgreed { get; set; }
    public AppRegistration AppRegistration { get; set; }
}

I have marked IsAgreementChecked as NotMapped because I only want to store the DateTime when the user clicked the Agree checkbox. When I generate the Controller based on this model and try to use the Create page. All the fields validate properly but the checkbox is ignored. In other words, the checkbox does not trigger any sort of validation. Any ideas? Thanks.

sakura-bloom
  • 4,524
  • 7
  • 46
  • 61
  • possible duplicate of [How do I make a checkbox required on an ASP.NET form?](http://stackoverflow.com/questions/1228112/how-do-i-make-a-checkbox-required-on-an-asp-net-form) – Kyle Trauberman May 08 '13 at 17:35
  • 1
    don't think it's a duplicate, I am using ASP.NET MVC 4, not Web Forms. – sakura-bloom May 08 '13 at 17:38
  • 1
    Actually this is not a duplicate, that question is specifically for doing validation using WebForms with the Validator control. This is done in MVC using DataAttributes. – Nick Albrecht May 08 '13 at 17:38
  • Ok, in that case, check this out: http://blog.degree.no/2012/03/validation-of-required-checkbox-in-asp-net-mvc/ – Kyle Trauberman May 08 '13 at 17:39

2 Answers2

3

It depends on what you want to do:

  • If you want to check whether a value is specified (true or false):

Make your Boolean Nullable:

[Required]
[Display(Name = "I agree to Participation Agreement")]
[NotMapped]
public bool? IsAgreementChecked { get; set; }

The solution proposed does exactly what you want. They basically create a new DataAnnotation. With the existing ones this is not possible.

At the moment, your required-attribute just checks whether a value was specified. Since a boolean is either true or false, the validation will never fail.

Community
  • 1
  • 1
Kenneth
  • 28,294
  • 6
  • 61
  • 84
  • Thanks for the answer. But how would I user the compare attribute. I mean, what would I compare the checkbox to? – sakura-bloom May 08 '13 at 17:35
  • Hm, scratch that, I thought you could compare it with a fixed value, which you can't actually. My apologies – Kenneth May 08 '13 at 17:37
  • Using something like this... [Enforcing a model's boolean value to be true using data annotations](http://stackoverflow.com/questions/6986928/enforcing-a-models-boolean-value-to-be-true-using-data-annotations) – Nick Albrecht May 08 '13 at 17:42
  • Yes, I also updated my answer with a link to another thread that does exactly what you want – Kenneth May 08 '13 at 17:42
  • For future searches, don't forget to add `using System.ComponentModel.DataAnnotations;` for `ValidationAttribute` when you're putting your custom validation logic in a separate class. – sakura-bloom May 08 '13 at 18:03
1

Here's a blog post describing how to do this:

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

The below code comes from this post

Basically, you can create a custom ValidationAttribute

public class BooleanRequiredAttribute : ValidationAttribute, IClientValidatable
{
    public override bool IsValid(object value)
    {
        if (value is bool)
            return (bool)value;
        else
            return true;
    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(
        ModelMetadata metadata,
        ControllerContext context)
    {
        yield return new ModelClientValidationRule
                            {
                                ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()),
                                ValidationType = "booleanrequired"
                            };
    }
}

Then apply it to your model instead of the [Required] attribute.

[BooleanRequired(ErrorMessage = "You must accept the terms and conditions.")]
Kyle Trauberman
  • 25,414
  • 13
  • 85
  • 121