简体   繁体   中英

How to use Data Annotations to validate a nullable int

In an MVC 5 project, I have a model with a nullable int. For reasons that might not be productive to explain, it needs to be an nullable int and cannot be a string.

// Value can be null or an integer from 0 to 145        
[Range(0,145)]
public int? Criterion { get; set; }

The intended annotation is to provide user feedback when entering a value in a form.

Criterion: @Html.TextBoxFor(m => m.Criterion)
<span class="text-danger">@Html.ValidationMessageFor(m => m.Criterion)</span>

While the user does get feedback when entering non-integer values, the Range attribute does not appear to work.

In order to enforce a nullable integer range, will I need to use regular expressions, or is there a simpler way to enforce the rule?

If I remember correctly, the [Range] data annotation should work as expected for nullable integers (ie it will only validate that a number falls within the range if one is present). You'll need to ensure that you are calling ModelState.IsValid within your POST action in order to trigger this server-side validation.

Example

The example below demonstrates using null , -1 , 1 and 150 as input values along with their expected results :

在此输入图像描述

You can see an example demonstrating this here .

I know this is old but I had the same situation today, Just in case someone else is having the same problem you need to know that Range does not validate the null value, but you can use it with Required to make the validation possible, it would be:

[Required, Range(0, 145)]
public int? Criterion  { get; set; }

Here's an example based on Rion's fiddle: https://dotnetfiddle.net/SBoqJA

You can create a custom data annotation to do this pretty easily by inheriting ValidationAttribute and IClientValidatable .

public class ValidateNullableInt : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        return IsValid(value != null ? value : null)
    }

    public override ValidationResult IsValid(object value, ValidationContext context)
    {
        bool isValid = false;
        if(typeof(value) == Nullable<int>)
        {
            int? temp = value as Nullable<int>;

            if(temp.HasVaue > minValue && temp.HasValue < maxValue)
            {
                return ValidationResult.Success;
            }

            return new ValidatonResult(errorMessage);
        }
    }
}

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