I\'ve got a view model like this:
public class SignUpViewModel
{
[Required(ErrorMessage = \"Bitte lesen und akzeptieren Sie die AGB.\")]
[DisplayName
I'm just taking the best of the existing solutions and putting it together into a single answer that allows for both server side and client side validation.
///
/// Validation attribute that demands that a value must be true.
///
/// Thank you http://stackoverflow.com/a/22511718
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
public class MustBeTrueAttribute : ValidationAttribute, IClientValidatable
{
///
/// Initializes a new instance of the class.
///
public MustBeTrueAttribute()
: base(() => "The field {0} must be checked.")
{
}
///
/// Checks to see if the given object in is true .
///
/// The value to check.
/// true if the object is a and true ; otherwise false .
public override bool IsValid(object value)
{
return (value as bool?).GetValueOrDefault();
}
///
/// Returns client validation rules for values that must be true.
///
/// The model metadata.
/// The controller context.
/// The client validation rules for this validator.
public IEnumerable GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
if (metadata == null)
throw new ArgumentNullException("metadata");
if (context == null)
throw new ArgumentNullException("context");
yield return new ModelClientValidationRule
{
ErrorMessage = FormatErrorMessage(metadata.DisplayName),
ValidationType = "mustbetrue",
};
}
}
jQuery.validator.addMethod("mustbetrue", function (value, element) {
return element.checked;
});
jQuery.validator.unobtrusive.adapters.addBool("mustbetrue");