Max Bündchen
Max Bündchen

Reputation: 1394

ASP.NET MVC 4 Custom Validation

How I can develop a custom validation rule in MVC? I.e. I have many decimal properties in my model and I would like to make a range validation from 1 to 100 to all of them without use data annotation in each.

Upvotes: 1

Views: 157

Answers (1)

Rui
Rui

Reputation: 4886

You can add validation to your whole model by making it implement IValidatableObject, for example:

public class MyModel: IValidatableObject
{
  public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
  {
     if (MyProperty > 100 || MyProperty < 1)
       yield return new ValidationResult("MyProperty is out of range (1..100)", new [] { "MyProperty" });
     ...

  }
}

Here's a resource that has a more elaborate example.

In case you want to cover all decimal properties automatically you can do this:

public abstract class MyValidatableBaseModel: IValidatableObject
{
  protected abstract virtual Type GetSubClassType();

  public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
  {
     var decimalProperties = GetSubClassType().GetProperties().Where(p => p.PropertyType == typeof(decimal));
     foreach (var decimalProperty in decimalProperties)
     {
        var decimalValue = (decimal)decimalProperty.GetValue(this, null);
        var propertyName = decimalProperty.Name;
        //do validation here and use yield return new ValidationResult
     } 
  }
}

public class MyModel : MyValidatableBaseModel
{
    protected override Type GetSubClassType()
    {
        return GetType();
    }
}

Any model that inherits from MyValidatableBaseModel (in the example, MyModel) and overrides GetSubClassType to returns it's own type will have that automatic validation for decimal properties

Upvotes: 1

Related Questions