3

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

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. I had managed to create a very similar method since I posted, so I know that it works precisely how I want it now!
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.