简体   繁体   中英

Data annotation to allow only whole numbers for long data type properties

I have a class as below,

    public class MyClass
    {
        [Required]
        public string Name { get; set; }

        [Required]
        [Range(1, Int64.MaxValue)]
        public long Volume{ get; set; }
    }

And used the above class in controller action.

[HttpPost]
public void testAction(, MyClass myClass)
{
var state = ModelState.IsValid;
}

Passing the json input for the controller action

Input type 1: {

"Name":"SomeName",
"Volume":12.2

}

No modal validation failure, and the input data mapped Volume property as 12.

Input type 2: {

"Name":"SomeName",
"Volume": "12.2"

}

Model validation error, "Error converting value "12.2" to type 'System.Int64'."

I want the same model validation failure error even input provide as "Volume":12.2

How to achieve this?

Thanks in advance.

You can create your own ValidationAttribute .

(inputVal % 1) == 0 make sure the input value isn't float number.

public class RangeCustomerAttribute : ValidationAttribute
{
    public long MaxValue { get; set; }
    public long MinValue { get; set; }

    public RangeCustomerAttribute(long minVal, long maxVal)
    {
        MaxValue = maxVal;
        MinValue = minVal;
    }
    public override bool IsValid(object value)
    {
        int inputVal;
        if (value == null)
            return false;

        if (int.TryParse(value.ToString(), out inputVal))
        {

            if (inputVal >= MinValue && inputVal <= MaxValue)
                return (inputVal % 1) == 0;

        }
        return false;
    }
}

use like

public class MyClass
{
    [Required]
    public string Name { get; set; }

    [Required]
    [RangeCustomer(1, Int64.MaxValue)]
    public long Volume{ get; set; }
}

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