C# add validation on a setter method

前端 未结 5 1153
花落未央
花落未央 2020-12-03 05:58

I have a a couple of variables that i define in C# by:

public String firstName { get; set; }
public String lastName { get; set; }
public String organization          


        
5条回答
  •  甜味超标
    2020-12-03 06:39

    It's best practice to apply SRP. Set the validation in a separate class.

    You can use FluentValidation

           Install-Package FluentValidation
    

    You would define a set of validation rules for Customer class by inheriting from AbstractValidator:

    Example:

      public class CustomerValidator : AbstractValidator {
        public CustomerValidator() {
          RuleFor(x => x.Surname).NotEmpty();
          RuleFor(x => x.Forename).NotEmpty().WithMessage("Please specify a first name");
          RuleFor(x => x.Discount).NotEqual(0).When(x => x.HasDiscount);
          RuleFor(x => x.Address).Length(20, 250);
          RuleFor(x => x.Postcode).Must(BeAValidPostcode).WithMessage("Please specify a valid postcode");
        }
    
        private bool BeAValidPostcode(string postcode) {
          // custom postcode validating logic goes here
        }
      }
    

    To run the validator, instantiate the validator object and call the Validate method, passing in the object to validate.

       Customer customer = new Customer();
       CustomerValidator validator = new CustomerValidator();
    
       ValidationResult result = validator.Validate(customer);
    
     if(! results.IsValid) {
       foreach(var failure in results.Errors) {
           Console.WriteLine("Property " + failure.PropertyName + " failed validation. Error was: " + failure.ErrorMessage);
    

    } }

提交回复
热议问题