Model require in mvc

Total Post:134

Points:940
 1182  View(s)
Ratings:
Rate this:
Is there a way through data annotations to require that a boolean property be set to true?
public class MyAwesomeObj
{
    public bool ThisMustBeTrue { get; set; }
}

  1. Post:194

    Points:1396
    Re: Model require in mvc

    You could create your own validator:

    public class IsTrueAttribute : ValidationAttribute
            {
                #region Overrides of ValidationAttribute
                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;
                }
     
                #endregion
            }

      Modified On Apr-05-2018 11:37:45 PM

Answer