Question

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?

Was it helpful?

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; }
    }
}

OTHER TIPS

xVal treats a required field dataannotation on a checkbox, as must be checked. I had to work around this situation recently as I was trying to represent a non-nullable boolean where the checkbox could be true or false (just not null). But in your case this works out perfectly. However, it gives a required field validation message where you are perhaps looking for a "must accept these terms" type message.

It might be easiest to use the xval remote rule validation, and validate from an ajax resource.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top