简体   繁体   中英

How to validate range of a nullable property in c#?

I have a model in which some properties are nullable. And they have a range attribute also. But the modelstate is not checking the range attribute validation.

Here is my property:

    [Range(0, 9223372036854775807L)]
    public long? OfferId { get; set; }

First of all if you expect your offer_id (it's not a good naming convention in c# btw - properties should be pascal case eg OfferId) then the type should be long? . Also if the property is nullable then the Range annotation will only be checked if it's not null. To sum up all you have to do is:

[Range(0, 9223372036854775807L)]
public long? OfferId { get; set; }

10 will pass
-10 will fail
null will pass

If you would like the null to not pass you can also add the [Required] annotation next to Range one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM