3

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"?

znn
  • 387
  • 5
  • 14
  • 1
    [Here](https://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations(v=vs.110).aspx) is the list of all DataAnnotation attributes available. Fast answer: no, there's none – Camilo Terevinto Jul 21 '18 at 14:26
  • 1
    There is no built in `ValidationAttribute`, but you can use a [foolproof](https://archive.codeplex.com/?p=foolproof) `[NotEqualTo]` attribute, or if you want to learn to write your own conditional validation attributes, refer [The Complete Guide To Validation In ASP.NET MVC 3 - Part 2](https://www.devtrends.co.uk/blog/the-complete-guide-to-validation-in-asp.net-mvc-3-part-2) –  Jul 21 '18 at 22:27

3 Answers3

5

Regex to the rescue:

public class MyModel
{
    [RegularExpression("(.*[1-9].*)|(.*[.].*[1-9].*)")]
    public double WhateverButNotZero { get; set; }
}
SBFrancies
  • 3,498
  • 2
  • 12
  • 34
1

try using regex annotation

public class MyModel
{
    [RegularExpression("^(?!0*(\.0+)?$)(\d+|\d*\.\d+)$", ErrorMessage = "Not Equal to Zero")]
    public double WhateverButNotZero { get; set; }
}
Wei Lin
  • 3,307
  • 2
  • 13
  • 35
1

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.

Parag
  • 38
  • 8
  • thanks for the answer, but what I'm looking for is "any number but zero". This means micro negatives or positives should be accepted, such as -0.0001, -0.0000000000001, 0.0123, etc – znn Jul 22 '18 at 16:25
  • In that case, I think "^[+-]?([0-9]\.\d+)|([1-9]\d*\.?\d*)$", this regular expression will be helpful, it will allow micro negatives or positives integers. – Parag Jul 22 '18 at 17:05