create some code that will run predefined rules against any dto object in csharp

To create a solution for validating DTO objects against predefined rules in C#, you could follow these steps:

  1. Define a set of validation rule objects that implement a common interface. For example:
main.cs
public interface IValidationRule<T>
{
    bool IsValid(T value);
}
67 chars
5 lines
  1. Implement the validation logic for each rule.
main.cs
public class RequiredFieldRule<T> : IValidationRule<T>
{
    private readonly string _fieldName;

    public RequiredFieldRule(string fieldName)
    {
        _fieldName = fieldName;
    }

    public bool IsValid(T value)
    {
        var fieldValue = value.GetType().GetProperty(_fieldName)?.GetValue(value, null);
        return fieldValue != null;
    }
}
361 chars
16 lines
  1. Create a validator class that will apply a set of rules to a DTO object.
main.cs
public class DtoValidator<T>
{
    private readonly List<IValidationRule<T>> _rules;

    public DtoValidator(List<IValidationRule<T>> rules)
    {
        _rules = rules;
    }

    public bool IsValid(T dto)
    {
        return _rules.All(rule => rule.IsValid(dto));
    }
}
278 chars
15 lines
  1. Instantiate the validator class and pass in the list of validation rules to apply.
main.cs
var rules = new List<IValidationRule<Customer>>();
rules.Add(new RequiredFieldRule<Customer>("FirstName"));
rules.Add(new RequiredFieldRule<Customer>("LastName"));
rules.Add(new RequiredFieldRule<Customer>("Email"));

var validator = new DtoValidator<Customer>(rules);
269 chars
7 lines
  1. Call the IsValid() method of the validator class passing in a DTO object to validate.
main.cs
var customer = new Customer { FirstName = "John", Email = "john@example.com" };
var isValid = validator.IsValid(customer);
123 chars
3 lines
  1. The IsValid() method will return true if all the validation rules pass, false otherwise.

gistlibby LogSnag