MODEL REQUIRE IN MVC

Tanuj Kumar

Total Post:134

Points:940
Posted by  Tanuj Kumar
 893  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. Kamlakar Singh

    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

            }

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!