mp3duck
mp3duck

Reputation: 2673

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

Upvotes: 3

Views: 1961

Answers (2)

xtrem
xtrem

Reputation: 1779

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.

Upvotes: 1

Tomasz Jaskuλa
Tomasz Jaskuλa

Reputation: 16033

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.

Upvotes: 3

Related Questions