Using ASP.Net MVC Data Annotation outside of MVC

前端 未结 1 438
花落未央
花落未央 2020-12-17 09:38

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,

相关标签:
1条回答
  • 2020-12-17 10:22

    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.

    0 讨论(0)
提交回复
热议问题