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.
You don’t need any data annotation for boolean properties. If the value is not
trueorfalsethe 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 accepttrueorfalse. 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
Requiredattribute:To ensure that the user checked the checkbox you could write a custom validation attribute:
and then: