1

When I have a checkbox in my form it is not enough to mark the matching property as Required because a true or false is sent as it's value.

Whats the best way to validate this in the model? I was thinking a regular expression to match the string true but I am either not writing it correctly or it does not work on a Boolean property.

public bool FeeAgree
    {
        get
        {
            return _feeAgree;
        }
        set
        {
            _feeAgree = value;
        }
    }

Above is the property I am trying to validate. Using the Required attribute does not work because the Html.CheckBoxFor creates a hidden field so there is always a valueof either true or false passed.

0

2 Answers 2

2

You don't need any data annotation for boolean properties. If the value is not true or false the default model binder will handle the case when trying to parse it and add a model error. So basically just by the fact of having such model property it would only accept true or false. Every other value would be considered as error.

If you were using a nullable boolean you could enforce it to have a value with the Required attribute:

[Required]
public bool? FeeAgree { get; set; }

To ensure that the user checked the checkbox you could write a custom validation attribute:

public class MustBeTrueAttribute : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        return value != null && (bool)value;
    }
}

and then:

[MustBeTrue(ErrorMessage = "You must accept the terms and conditions")]
public bool FeeAgree { get; set; }
Sign up to request clarification or add additional context in comments.

2 Comments

That's the problem, it always has a value... if the value is false (meaning they did not check the box) then I want to send an error back.
@JBeckton, OK, now I understand. Please see my update about the custom attribute.
1

This solution could be extended to include client side validation.

public class MustBeTrueAttribute : ValidationAttribute, IClientValidatable {

    public override bool IsValid(object value) {
        return value is bool && (bool)value;
    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(
        ModelMetadata metadata, ControllerContext context) {

        return new ModelClientValidationRule[] {
        new ModelClientValidationRule {
            ValidationType = "checkboxtrue",
            ErrorMessage = this.ErrorMessage
        }};
    }
}

Then if the view included a bit of jquery code to add the "checkboxtrue" validation type...

jQuery.validator.unobtrusive.adapters.add("checkboxtrue", function (options) {
    if (options.element.tagName.toUpperCase() == "INPUT" && options.element.type.toUpperCase() == "CHECKBOX") {
        options.rules["required"] = true;
        if (options.message) {
            options.messages["required"] = options.message;
        }
    }
});

The result is client-side checkbox validation

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.