23

i was wondering if there is a way to use ASP.Net's Data annotation without the MVC site.

My example is that i have a class that once created needs to be validated, or will throw an error. I like the data annotations method, instead of a bunch of if blocks fired by the initaliser.

Is there a way to get this to work?

I thought it would be something like:

  • Add data annotations
  • Fire a method in the initialiser that calls the MVC validator on the class

any ideas? i must admit i havent added the MVC framework to my project as i was hoping i could just use the data annotations class System.ComponentModel.DataValidation

Doug
  • 6,460
  • 5
  • 59
  • 83
  • I created my own version of the DataValidation class, I can possibly outsource it if people are interested. It was done before MVC2, and can accommodate more complex cases. – Yuriy Faktorovich Jun 22 '10 at 02:30

1 Answers1

33

Here's an example:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

public class Foo
{
    [Required(ErrorMessage = "the Bar is absolutely required :-)")]
    public string Bar { get; set; }
}

class Program
{
    public static void Main()
    {
        var foo = new Foo();
        var results = new List<ValidationResult>();
        var context = new ValidationContext(foo, null, null);
        if (!Validator.TryValidateObject(foo, context, results))
        {
            foreach (var error in results)
            {
                Console.WriteLine(error.ErrorMessage);
            }
        }
    }
}

But quite honestly FluentValidation is much more powerful.

Jeroen K
  • 10,258
  • 5
  • 41
  • 40
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • 3
    I was looking for a .Net 3.5 solution - ValidationContext is not available before .Net 4.0 – Doug Jun 23 '10 at 12:12
  • 1
    @Doug might want to put that as a req in the question. – Nate-Wilkins Oct 22 '14 at 02:27
  • 1
    Unfortunately, this validation doesn't recurse through any complex child objects or collections. The Validator.TryValidateObject(...) just does immediate property and field validations, and calls it a day, as opposed the the validation that happens on model binding in the Controller in MVC world which traverse the entire object graph. – neumann1990 Nov 03 '16 at 20:32
  • 3
    In my case, the call to `TryValidateObject` as written only checks the `RequiredAttribute`. If you'd like to use other validators from `System.ComponentModel.DataAnnotations` like `MaxLengthAttribute`, add `true` for the fourth argument (`validateAllProperties`). See the accepted answer at https://stackoverflow.com/questions/5368672/validator-tryvalidateobject-not-validating-rangeattribute – Don Rowe Jun 20 '17 at 22:30