erli
erli

Reputation: 408

Require boolean attribute on model to be false or empty

How can I use annotations to require a boolean model property to be either false or empty?

Example:

// model
public class MyModel 
{
  public string StringProperty { get; set; }
  public bool BoolProperty { get; set; }
}

OK:

POST /someEndpoint
{
  "stringProperty": "foobar"
}

POST /someEndpoint
{
  "stringProperty": "foobar",
  "boolProperty": false
}

400:

POST /someEndpoint
{
  "stringProperty": "foobar",
  "boolProperty": true
}

I want to validate the model using ModelState.IsValid. So far, I've tried using [Range(typeof(bool), "false", "false")] but ModelState.IsValid returns true even if boolProperty is set to true. Any help?

Upvotes: 1

Views: 478

Answers (1)

Serge
Serge

Reputation: 43929

I created a custom validation attribute and it works for me

    public class AllowedOnlyFalse : ValidationAttribute
    {
        public override bool IsValid(object value)
        {
            if (value == null) return true;
            bool val = Convert.ToBoolean(value);
            return !val;
        }
    }

    // model
    public class MyModel
    {
        public string StringProperty { get; set; }

        [AllowedOnlyFalse]
        public bool BoolProperty { get; set; }
    }

Upvotes: 1

Related Questions