Home > DeveloperSection > Forums > Model require in mvc
Tanuj Kumar

Total Post:134

Points:940
Posted on    October-10-2014 2:32 AM

 ASP.NET MVC ASP.Net  ASP.NET MVC 
Ratings:


 1 Reply(s)
 667  View(s)
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; }

}



Kamlakar Singh
Kamlakar Singh

Total Post:194

Points:1396
Posted on    October-10-2014 2:33 AM

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

        }


Don't want to miss updates? Please click the below button!

Follow MindStick