Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

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

DZone's Guide to

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

· Agile Zone
Free Resource

See how three solutions work together to help your teams have the tools they need to deliver quality software quickly. Brought to you in partnership with CA Technologies

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.

Discover how TDM Is Essential To Achieving Quality At Speed For Agile, DevOps, And Continuous Delivery. Brought to you in partnership with CA Technologies

Topics:

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

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}