Search code examples
c#asp.net-mvcdata-annotations

MVC 5 Data Annotation "Not Equal to 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"?


Solution

  • 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.

    1. Create a class that extends the ValidationAttribute class
    2. Override the IsValid(object value) method
    3. Inside your validation method, convert the object to int and check if it's equal zero
    public 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; }
    }