WHY RANGE DATA ANNOTATION IS NOT WORKING ON CHECKBOX IN CLIENT SIDE?

Chintoo Semi

Total Post:135

Points:947
Posted by  Chintoo Semi
 1947  View(s)
Ratings:
Rate this:

I have a form with some fields with the Required Data Annotation and then i have a "Accept Terms and Conditions" checkbox with the Data Annotation [Range(typeof(bool), "true", "true", ErrorMessage="You must accept Terms And Conditions to proceed")] Everything works fine but the thing that is annoying is that the Required Data Annotation fires the errors before post.. i mean, i click on submit and the form does not make a post and it shows the errors but with the Range, the form post and then shows the errors.

Why is that? is that a common behavior?

  1. Pravesh Singh

    Post:412

    Points:2888
    Re: Why Range Data Annotation is not working on checkbox in client side?

    Hi Chintoo,

    public class EnforceTrueAttribute : ValidationAttribute, IClientValidatable

        {

            public override bool IsValid(object value)

            {

                if (value == null) return false;

                if (value.GetType() != typeof(bool)) throw new InvalidOperationException("can only be used on boolean properties.");

                return (bool)value == true;

            }

            public override string FormatErrorMessage(string name)

            {

                return "The " + name + " field must be checked in order to continue.";

            }

            public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)

            {

                yield return new ModelClientValidationRule

                {

                    ErrorMessage = String.IsNullOrEmpty(ErrorMessage) ? FormatErrorMessage(metadata.DisplayName) : ErrorMessage,

                    ValidationType = "enforcetrue"

                };

            }

        }

    And in my JS:

    jQuery.validator.addMethod("enforcetrue", function (value, element, param) {

                return element.checked;

            });

            jQuery.validator.unobtrusive.adapters.addBool("enforcetrue");

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!