Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Web Api 2: [Required] for value types?

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?

like image 528
Dave New Avatar asked Feb 27 '26 16:02

Dave New


1 Answers

you can use the range attribute.

[Range(0, 99)]
public double MyDouble { get; set; }
like image 146
Yousuf Avatar answered Mar 01 '26 04:03

Yousuf