What is the best way to add a validator greater than 0 on the client side using MVC and data annotation?

I would like to be able to only allow form submission if the value in a specific field is greater than 0. I thought it was possible that the Mvc range attribute would allow me to enter only one value to indicate only the larger test value, but it was unlucky as it insists on minimum and maximum values.

Any ideas on how this can be achieved?

+68
asp.net-mvc unobtrusive-validation
Sep 14 '11 at 15:47
source share
4 answers

You cannot store a number larger than your base data type, which can be stored, so the fact that the Range attribute requires a maximum value is very good. Remember that ∞ does not exist in the real world, so the following should work:

 [Range(1, int.MaxValue, ErrorMessage = "Please enter a value bigger than {1}")] public int Value { get; set; } 
+192
Sep 14 '11 at 15:57
source share

I found this answer, trying to confirm any positive value for a floating point number / double. Turns out these types have a useful constant for Epsilon.

Represents the smallest positive System.Double value that is greater than zero.

  [Required] [Range(double.Epsilon, double.MaxValue)] public double Length { get; set; } 
+5
Jul 20 '18 at 7:42
source share

You can currently (nu) get the Data Annotation Extensions that Min and Max provide, functioning just as you would expect from them.

+1
Aug 20 '15 at 7:26
source share

You can create your own validator, for example like this:

  public class RequiredGreaterThanZero : ValidationAttribute { /// <summary> /// Designed for dropdowns to ensure that a selection is valid and not the dummy "SELECT" entry /// </summary> /// <param name="value">The integer value of the selection</param> /// <returns>True if value is greater than zero</returns> public override bool IsValid(object value) { // return true if value is a non-null number > 0, otherwise return false int i; return value != null && int.TryParse(value.ToString(), out i) && i > 0; } } 

Then include this file in your model and use it as an attribute:

  [RequiredGreaterThanZero] [DisplayName("Driver")] public int DriverID { get; set; } 

I usually use this when checking a dropdown.

0
Apr 17 '19 at 20:25
source share



All Articles