Tuesday, April 25, 2017

MVC validation of a checkbox


public class BooleanRequiredAttribute : ValidationAttribute, IClientValidatable
    {
        public override bool IsValid(object value)
        {
            if (value is bool)
                return (bool)value;
            else
                return true;
        }

        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(
            ModelMetadata metadata,
            ControllerContext context)
        {
            yield return new ModelClientValidationRule
            {
                ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()),
                ValidationType = "booleanrequired"
            };
        }
    }

================

 public class BATModel
    {
        [BooleanRequired(ErrorMessage = "Please agree to terms to proceed")]
        public bool AgreedToTerms { get; set; }      


}

===================

InView:

 <script type="text/javascript">
    (function ($) {
        $.validator.unobtrusive.adapters.addBool("booleanrequired", "required");
    } (jQuery));
    </script>



 @using (Html.BeginForm("Page1Questions", "AssetmarkBAT", FormMethod.Post))
        {
            <div>
                @Html.CheckBoxFor(m => m.AgreedToTerms)
                @Html.ValidationMessageFor(x => Model.AgreedToTerms)
                <input type="submit" value="Submit" />
            </div>
            
        }

No comments:

Post a Comment