Probably I am missing something, but having the model below
public class MyModel
{
public double WhateverButNotZero { get; set; }
}
is there any MVC built-in DataAnnotation to validate the number as "everything but zero"?
Probably I am missing something, but having the model below
public class MyModel
{
public double WhateverButNotZero { get; set; }
}
is there any MVC built-in DataAnnotation to validate the number as "everything but zero"?
public class MyModel
{
[RegularExpression("(.*[1-9].*)|(.*[.].*[1-9].*)")]
public double WhateverButNotZero { get; set; }
}
There is no built-in validation for that specifically, but you can create a custom attribute for it if you don't want to use regex as mentioned in other answers.
ValidationAttribute
classIsValid(object value)
methodint
and check if it's equal zeropublic class NotZeroAttribute : ValidationAttribute
{
public override bool IsValid(object value) => (int)value != 0;
}
Then just use it on your class property like that:
public class MyModel
{
[NotZero]
public double WhateverButNotZero { get; set; }
}
try using regex annotation
public class MyModel
{
[RegularExpression("^(?!0*(\.0+)?$)(\d+|\d*\.\d+)$", ErrorMessage = "Not Equal to Zero")]
public double WhateverButNotZero { get; set; }
}
You can use RegularExpression DataAnnotation attribute.
[RegularExpression(@"^\d*[1-9]\d*$")]
public double WhateverButNotZero { get; set; }
Hopefully, What is the regex for “Any positive integer, excluding 0” will be helpful to find out the regular expression as per your need.
Way I do it, and I think the easiest way
[Range(1, int.MaxValue, ErrorMessage = "Value must be greater than zero.")]