1

This is an extension of an older question from this post:

Enforcing a model's boolean value to be true using data annotations

This gave me a lot of insight on how to get the client side custom validation working with jquery-unubtrusive-ajax.js.

Here is the answer code:

            namespace Checked.Entitites
            {
                public class BooleanRequiredAttribute : ValidationAttribute, IClientValidatable
                {
                    public override bool IsValid(object value)
                    {
                        return value != null && (bool)value == true;
                    }

                    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
                    {
                        //return new ModelClientValidationRule[] { new ModelClientValidationRule() { ValidationType = "booleanrequired", ErrorMessage = this.ErrorMessage } };
                        yield return new ModelClientValidationRule() 
                        { 
                            ValidationType = "booleanrequired", 
                            ErrorMessage = this.ErrorMessageString 
                        };
                    }
                }
            }
  • When i use this custom attribute in my models it works fine. ex:

            [BooleanRequired(ErrorMessage = "Please accept the terms")]
            public bool Terms { get; set; }
    
  • When i use textboxfor in my views the error messages populate in the html validation summary.

            @Html.CheckBoxFor(model => model.Terms, new { @class = "legalbox",  @placeholder = "Terms" })
    
  • I also had to add this line to my jquery.unubtrusive-ajax.js

            $.validator.unobtrusive.adapters.addBool("BooleanRequired", "required"); 
    

The issue i am having with this fix arises when i reference this model in the controller and check the modelstate. The modelstate is always false no matter what i have as the value for this custom validated field. It looks like the override isvalid is working in the client side validation but not on the server side. I need it to work on both and have been scouring trying to find a solution that isn't "ditch dataannotations and use something else".

The specific line i am using in my controller that will never pass with this field is as follows:

            if (ModelState.IsValid) {
                 //Logic here
            }

The rest of the model using the standard data-annotations validate correctly, i just cannot get this custom one to work the same way as the built in attributes. Its possible that the right solution would prevent me from having to add that line to the unobtrusive ajax file.

Any help would be appreciated.

Thanks

Community
  • 1
  • 1
Chris Limina
  • 113
  • 1
  • 1
  • 7

0 Answers0