Validate checkbox - frontend MVC3
I have created the following custom attribute to assist me with validating a required checkbox field:
public class CheckboxRequired : ValidationAttribute, IClientValidatable
{
public CheckboxRequired()
: base("required") { }
public override bool IsValid(object value)
{
return (bool)value == true;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
ModelClientValidationRule rule = new ModelClientValidationRule();
rule.ErrorMessage = FormatErrorMessage(metadata.GetDisplayName());
rule.ValidationType = "mandatory";
yield return rule;
}
}
However, I am trying to get it t开发者_C百科o trigger client side, and not when I call my ActionResult (if (ModelState.IsValid)
)
The validation does work when I call my ActionResult, but I'd prefer it to validate before getting that far.
What modifications do I need to make to make the validation kick in client side?
Thanks
In order to implement the client side you can add for example a jQuery validator method and an unobtrusive adapter (simple example):
// Checkbox Validation
jQuery.validator.addMethod("checkrequired", function (value, element)
{
var checked = false;
checked = $(element).is(':checked');
return checked;
}, '');
jQuery.validator.unobtrusive.adapters.addBool("mandatory", "checkrequired");
I hope it helps.
How about the old good Regex?
[RegularExpression("^(true|True)$", ErrorMessage="Required...")]
public bool AgreeWithTos { get; set; }
Accepts both "true", and 'True' as javascript and .NET format booleans differently.
精彩评论