public class Person { [Required(ErrorMessage = "Name is required")] public string Name { get; set; } } var person = new Person { Name = "" }; var context = new ValidationContext(person); Validator.TryValidateObject(person, context, results, true); if (results.Any()) { foreach (var result in results) { Console.WriteLine(result.ErrorMessage); } }
public class Book { [Range(0, int.MaxValue, ErrorMessage = "Pages must not be negative")] public int Pages { get; set; } } var book = new Book { Pages = -10 }; var context = new ValidationContext(book); Validator.TryValidateObject(book, context, results, true); if (results.Any()) { foreach (var result in results) { Console.WriteLine(result.ErrorMessage); } }In this example, we use the Range attribute to specify that the Pages property must be between 0 and int.MaxValue. We then create a new instance of the Book class with a negative Pages property. We create a new ValidationContext and call the Validator.TryValidateObject method to validate the object. If any validation failures occur, we display the error message using the ErrorMessage property of the ValidationResult class. Package library: The ValidationContext class is part of the System.ComponentModel.DataAnnotations namespace, which is included in the .NET Standard library.