views:

197

answers:

2

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?

+1  A: 

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.

Jace Rhea
Luckily, the purpose for the checkbox is to act as a sign-off for a particular form, so the default message is perfectly appropriate in this case. Thanks @jacerhea. I only haven't marked this as the answer in case someone looking for a similar answer needs to leave a different message.
StuperUser
+1  A: 

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; }
    }
}
MHinton
Thanks @MHinton, this is useful for having to add a message other than the default. As the default message is appropriate, I will use the [Required] annotation as @jacerhea suggested.
StuperUser