apostolov
apostolov

Reputation: 1646

Best way of adding "different than" zero validation attribute

What is the best way of adding "Different than zero" validation attribute in ASP.NET MVC 3/4?

Upvotes: 1

Views: 467

Answers (1)

chridam
chridam

Reputation: 103425

I would assume you would want to add a custom validation attribute with the error message "Different than zero" (not sure of the correct English usage here). Say you have a model with a property that requires the validation:

public class YourModel
{
    [Required]
    [CheckZero] //custom attribute
    public int PropertyName { get; set; }   
    ...
}

Create a class CheckZeroAttribute that derives from ValidationAttribute and override one of the IsValid methods provided by the base class. Overriding the IsValid version taking a ValidationContext parameter provides more information to use inside the IsValid method (the ValidationContext parameter will give you access to the model type, model object instance, and friendly display name of the property you are validating, among other pieces of information).

public class CheckZeroAttribute : ValidationAttribute
{
    protected override ValidationResult IsValid (object value, ValidationContext validationContext)
    {
         //the error message
         string sErrorMessage = "Different from zero";
         //implement appropriate validation logic here
         ...
         if (...) { return new ValidationResult(sErrorMessage); }
         return ValidationResult.Success;
    }
}

Upvotes: 2

Related Questions