Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 to 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

like image 431
mp3duck Avatar asked Dec 17 '25 20:12

mp3duck


2 Answers

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.

like image 53
Tomasz Jaskuλa Avatar answered Dec 19 '25 10:12

Tomasz Jaskuλa


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.

like image 30
xtrem Avatar answered Dec 19 '25 11:12

xtrem