Reputation: 6607
How do I require a value of True
for a boolean
property in MVC 3 with .NET?
This is where I am, I need the value to be True
othewise it's not valid
<Required()> _
<DisplayName("Agreement Accepted")> _
Public Property AcceptAgreement As Boolean
Here is the fix in case the link dies someday
Add this class
Public Class BooleanMustBeTrueAttribute Inherits ValidationAttribute
Public Overrides Function IsValid(ByVal propertyValue As Object) As Boolean
Return propertyValue IsNot Nothing AndAlso TypeOf propertyValue Is Boolean AndAlso CBool(propertyValue)
End Function
End Class
Add attribute
<Required()> _
<DisplayName("Agreement Accepted")> _
<BooleanMustBeTrue(ErrorMessage:="You must agree to the terms and conditions")> _
Public Property AcceptAgreement As Boolean
Upvotes: 4
Views: 5806
Reputation: 5900
If anyone is interested in adding jquery validation (so that the checkbox is validated both in the browser and the server) you should modify the BooleanMustBeTrueAttribute class like so:
public class BooleanMustBeTrueAttribute : ValidationAttribute, IClientValidatable
{
public override bool IsValid(object propertyValue)
{
return propertyValue != null
&& propertyValue is bool
&& (bool)propertyValue;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
yield return new ModelClientValidationRule
{
ErrorMessage = this.ErrorMessage,
ValidationType = "mustbetrue"
};
}
}
Basically, the class now also implements IClientValidatable, and returns the corresponding js error message and the jquery validation attribute that will be added to HTML field ("mustbetrue").
Now, in order for the jquery validation to work, add the following js to the page:
jQuery.validator.addMethod('mustBeTrue', function (value) {
return value; // We don't need to check anything else, as we want the value to be true.
}, '');
// and an unobtrusive adapter
jQuery.validator.unobtrusive.adapters.add('mustbetrue', {}, function (options) {
options.rules['mustBeTrue'] = true;
options.messages['mustBeTrue'] = options.message;
});
Note: I based the previous code on the one used in this answer -> Perform client side validation for custom attribute
And that's basically it :)
Remember that for the previous js to work, you must have included the following js files in the page:
<script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
P.S. When you have it working, I would actually recommend adding the code to a js file in the Scripts folder, and create a bundle with all the js files.
Upvotes: 4