-1

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.

Magendran V
  • 1,411
  • 3
  • 19
  • 33

1 Answers1

0

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; }
}
D-Shih
  • 44,943
  • 6
  • 31
  • 51
  • Is there any build-in data annotation to allow only whole numbers? – Magendran V Sep 03 '18 at 12:10
  • I don't think there is built-in data annotation in c#, or you can write regex let it simple – D-Shih Sep 03 '18 at 12:16
  • Ok, But when API input "Volume":12.2 i.e with out double quote is automatically removes the .2 while input mapping to the class. How to restrict that as well? this will not work even with regular expression as the value mapped is 12 not 12.2. Any idea? – Magendran V Sep 04 '18 at 08:59