Skip to content

Instantly share code, notes, and snippets.

@hatelove
Created April 24, 2013 07:32
Show Gist options
  • Save hatelove/5450316 to your computer and use it in GitHub Desktop.
Save hatelove/5450316 to your computer and use it in GitHub Desktop.
// 要加入參考system.componentmodel.dataannotations.dll
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
using System.Reflection;
namespace ModelValidate
{
class Program
{
static void Main(string[] args)
{
var person = new Person
{
Id = 238,
Name = "kevin tan",
Birthday = new DateTime(2011, 1, 1)
};
ICollection<ValidationResult> results = new List<ValidationResult>();
var isValid = DataAnnotationsValidator.TryValidate(person, out results);
if (!isValid)
{
foreach (var validationResult in results)
{
foreach (var memberName in validationResult.MemberNames)
{
var value = person.GetType().GetProperty(memberName).GetValue(person, null);
Console.WriteLine("name:{0}, value:{1}, error message:{2}", memberName, value, validationResult.ErrorMessage);
Console.WriteLine();
}
}
}
else
{
Console.WriteLine("validate success");
}
}
}
public class Person
{
[Range(10, 1000)]
[RegularExpression(@"^2+?8$")]
public int Id { get; set; }
[Required(AllowEmptyStrings = false)]
[StringLength(6, MinimumLength = 3)]
public string Name { get; set; }
[Required]
[Range(typeof(DateTime), "2012/04/19", "2012/05/01")]
public DateTime? Birthday { get; set; }
}
public class DataAnnotationsValidator
{
public static bool TryValidate(object entity, out ICollection<ValidationResult> results)
{
var context = new ValidationContext(entity, serviceProvider: null, items: null);
results = new List<ValidationResult>();
return Validator.TryValidateObject(
entity, context, results,
validateAllProperties: true
);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment