3

Using the [Required] data annotation in Web Api input models only seems to check for reference types being instantiated to null:

public class MyInputModel
{
    [Required] // This works! ModelState fails.
    public CustomClass MyCustomProperty { get; set; }
}

How can we get this to work with value types WITHOUT the default instantiation?

public class MyInputModel
{
    [Required] // This is ignored because MyDouble is defaulted to 0
    public double MyDouble { get; set; }
}

Is the only way through using Nullable<Double>? Could we not create some custom validation attribute?

Dave New
  • 38,496
  • 59
  • 215
  • 394
  • You can always write custom validation attribute. E.g http://www.codeproject.com/Articles/260177/Custom-Validation-Attribute-in-ASP-NET-MVC – vijay shiyani Aug 12 '15 at 12:53

3 Answers3

4

you can use the range attribute.

[Range(0, 99)]
public double MyDouble { get; set; }
Yousuf
  • 3,105
  • 7
  • 28
  • 38
3

try making value type Nullable e.g. public double? MyDouble { get; set; }

vijay shiyani
  • 766
  • 7
  • 19
1

This is how the required attribute working internally.

 override bool IsValid(object value) {
        if (value == null) {
            return false;
        }

        // only check string length if empty strings are not allowed
        var stringValue = value as string;
        if (stringValue != null && !AllowEmptyStrings) {
            return stringValue.Trim().Length != 0;
        }

        return true;
    }

So nothing to do with the 0 value so you must check it with Range attribute

Ahmed H. Gomaa
  • 136
  • 1
  • 8