Search code examples
asp.net-mvcvalidationxvalboolean

Validate a bool that must be true using xVal


I have a business requirement to enforce a check box on a HTML form to be marked as true before allowing submission of the form.

I can return the user to the form if this box has not been checked with an appropriate message, but want to return all information from an xVal validation of the form data at the same time.

I can't find any information elsewhere, so is it possible to use xVal to validate a bool to true (or false), similar to using the [Range(min, max)] DataAnnotation or must I manually .AddModelError(..) containing this information to add the error to the ViewModel?


Solution

  • Have you tried creating your own ValidationAttribute? I created a TrueTypeAttribute for this sort of situation.

    using System;
    using System.ComponentModel.DataAnnotations;
    
    namespace KahunaCentralMVC.Data.ModelValidation.CustomValidationAttributes
    {
        public class TrueTypeAttribute : ValidationAttribute
        {
            public override bool IsValid(object value)
            {
                if (value == null) return false;
                bool newVal;
                try
                {
                    newVal = Convert.ToBoolean(value);
                    if (newVal)
                        return true;
                    else
                        return false;
                }
                catch (InvalidCastException)
                {
                    return false;
                }
            }
        }
    }
    
    [MetadataType(typeof(FooMetadata))]
    public partial class Foo
    {
        public class FooMetadata
        {
            [Required(ErrorMessage = " [Required] ")]
            [TrueTypeAttribute(ErrorMessage = " [Required] ")]
            public bool TruVal { get; set; }
        }
    }