Over a million developers have joined DZone.

Using ASP.NET MVC Validation Mechanism without ASP.NET MVC

· Agile Zone

Reduce testing time & get feedback faster through automation. Read the Benefits of Parallel Testing, brought to you in partnership with Sauce Labs.

I get used to DataAnnotations for model validation very quickly. Indeed, it is great approach. You attribute you model with corresponding attributes, rest is done by framework. It is only ModelState.IsValid, all you have to do before starting working with model.

During implementation of some feature for candidate.net I thought to myself, that I need need exactly same validation for my model class, but out of MVC framework. Namely, for some model class, like Github.cs I just want to know, is it "configured" or not. And configured == valid in my context. Instead of writing custom code with checking all required properties to have some values I wished to do the same as ASP.NET MVC does, through DataAnnotations. It turned out to be possible and really easy.

Basic start

Assume you have such model:

public class SimpleModel
{
 [Required]
 public string SomeProperty { get; set; }
 
 [Range(0,50)]
 public int SomeAnotherProperty { get; set; }
}

If your goal is just to get answer "yes or no", you can create such function:

public bool ValidateSimpleModel(SimpleModel validate)
{
 return Validator.TryValidateObject(validate, new ValidationContext(validate, null, null), null);
}

Validator is a static class in DataAnnotations namespace. It takes target object, validation context and validation results collection. But due, to it just "tries" to perform validation, most of all parameters could be null.

Use validation results

If you need more specific information, like which field is exactly invalid you need to have ICollection<ValidationResult>

public ICollection<ValidationResult> ValidateSimpleModel(SimpleModel validate)
{
 var validationResults = new List<ValidationResult>();
 Validator.TryValidateObject(validate, new ValidationContext(validate, null, null), validationResults);
 
 return validationResults;
}

In case of invalid object it would return non-empy collection of ValidationResult, that would contain all relevant information.

Wrapping up to extension method

Finally, you can create simple extension extension method and apply DataAnnotations validation to any kind of object:

public static class ValidatorExtensions
{
    public static bool TryValidateObject(this object validate)
    {
        return Validator.TryValidateObject(validate, new ValidationContext(validate, null, null), null);
    }
}

So, the model could just have IsValid() method, like:

public bool IsValid()
{
 return this.TryValidateObject();
}
It works great for such simple task I need to accomplish.

The Agile Zone is brought to you in partnership with Sauce Labs. Discover how to optimize your DevOps workflows with our cloud-based automated testing infrastructure.

Topics:

Published at DZone with permission of Alexander Beletsky, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}