The .NET Framework provides a set of attributes that we can use to validate objects. By using the namespace System.ComponentModel.DataAnnotations we can annotate our model's properties with validation attributes.
There are attributes to mark a property as required, set a maximum length, and so on. For example:
- public class Game
- {
- [Required]
- [StringLength(20)]
- public string Name { get; set; }
- [Range(0, 100)]
- public decimal Price { get; set; }
- }
- Validator.TryValidateObject(obj
- , new ValidationContext(obj)
- , results, true);
- static void Main(string[] args)
- {
- ICollection<ValidationResult> results = null;
- var invalidGame = new Game
- {
- Name = "My name is way over 20 characters",
- Price = 300,
- };
- if (!Validate(invalidGame, out results))
- {
- Console.WriteLine(String.Join("\n", results.Select(o => o.ErrorMessage)));
- }
- else
- {
- Console.WriteLine("I'm a valid object!");
- }
- Console.ReadKey(true);
- }
- static bool Validate<T>(T obj, out ICollection<ValidationResult> results)
- {
- results = new List<ValidationResult>();
- return Validator.TryValidateObject(obj, new ValidationContext(obj), results, true);
- }

- var validGame = new Game
- {
- Name = "Magicka",
- Price = 5,
- };

- public class DivisibleBy7Attribute : ValidationAttribute
- {
- public DivisibleBy7Attribute()
- : base("{0} value is not divisible by 7")
- {
- }
- protected override ValidationResult IsValid(object value, ValidationContext validationContext)
- {
- decimal val = (decimal)value;
- bool valid = val % 7 == 0;
- if (valid)
- return null;
- return new ValidationResult(base.FormatErrorMessage(validationContext.MemberName)
- , new string[] { validationContext.MemberName });
- }
- }
- [DivisibleBy7]
- public decimal Price { get; set; }


Bruno PétersonPosted Jul 3, 2015, 3:05 PM
Good one
NitinPosted May 30, 2015, 11:04 AM
Nice
Former memberPosted May 29, 2015, 9:35 AM
Interesting
Upendra Pratap ShahiPosted May 29, 2015, 7:54 AM
nice ..
Sibeesh VenuPosted May 29, 2015, 7:28 AM
Nice one.
Vivek TripathiPosted May 29, 2015, 6:46 AM
Good One