ValidationContext is a class in C# that is used for validating objects and properties. The AddError method of the ValidationContext class is used to add an error message to the list of validation errors for the specified object.
Example 1: Suppose we have a class named 'User' which has a property 'Age'. We want to validate that the age of the user is greater than or equal to 18. We can use the following code to achieve that:
public class User { public int Age { get; set; } }
public class UserValidator { public static IEnumerable Validate(User user) { ValidationContext context = new ValidationContext(user); if(user.Age < 18) { context.AddError("Age must be greater than or equal to 18"); } return context.Errors.Select(e => e.ErrorMessage); } }
Example 2: Suppose we have a class named 'Payment' which has a property 'Amount'. We want to validate that the amount of payment is positive. We can use the following code to achieve that:
public class Payment { public decimal Amount { get; set; } }
public class PaymentValidator { public static IEnumerable Validate(Payment payment) { ValidationContext context = new ValidationContext(payment); if(payment.Amount <= 0) { context.AddError("Amount must be positive"); } return context.Errors.Select(e => e.ErrorMessage); } }
Both of these examples use the Validate method to validate the object and return a list of error messages. These examples use the ValidationContext class which is part of the System.ComponentModel namespace in the .NET framework.
C# (CSharp) ValidationContext.AddError - 34 examples found. These are the top rated real world C# (CSharp) examples of ValidationContext.AddError extracted from open source projects. You can rate examples to help us improve the quality of examples.