Boolean True for the required attribute of the MVC.net property

How do I get the True value for the boolean property in MVC 3 with .NET? This is where I am, I need the value to be True otherwise it is invalid

 <Required()> _ <DisplayName("Agreement Accepted")> _ Public Property AcceptAgreement As Boolean 

Here is a 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 
+4
source share
1 answer

If someone is interested in adding jquery validation (so that the checkbox is checked both in the browser and on the server), you should change the BooleanMustBeTrueAttribute class as follows:

 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, which will be added to the HTML field ("mustbetrue").

Now, to check if jquery is working properly, 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 a custom attribute

And that basically it :)

Remember that for the previous js to work, you had to include the following js files on 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> 

PS When you have a job, I would recommend adding the code in the js file to the Scripts folder and creating a package with all js files.

+4
source

All Articles