Asp.net Core – Centralising FluentValidation rules to a service
This is quite an easy thing to do, might not be work blogging, but hey – might save you few minutes in the future.
This is ho your AbstractValidator looks like.
public class CommandValidator : AbstractValidator<Command> { public CommandValidator(IFieldValidatorService validatorService) { RuleFor(x => x.Name).NotNull().NotEmpty(); RuleFor(x => x.StartDate).NotNull().NotEmpty().Must(validatorService.ValidDate).WithMessage(ValidationMessages.Project.StartDate); RuleFor(x => x.StartDate).Must(validatorService.GreaterThanToday).WithMessage(ValidationMessages.Project.StartDateGreaterThanToday); RuleFor(x => x.EndDate).NotNull().NotEmpty().Must(validatorService.ValidDate).WithMessage(ValidationMessages.Project.EndDate); RuleFor(x => x.Image).Must(validatorService.ValidProjectImageAllowedFileType).WithMessage(ValidationMessages.Project.Image); } }
This is the service implementation
public class FieldValidatorService : IFieldValidatorService { public bool ValidDate(DateTime date) { return !date.Equals(default(DateTime)); } public bool GreaterThanToday(DateTime date) { if(date > DateTime.UtcNow) return true; return false; } public bool ValidProjectImageAllowedFileType(PostedFile image) { string[] allowedFileTypes = { ".jpg", ".png" }; if (image == null) return true; if (string.IsNullOrWhiteSpace(image.FileName)) return false; if (!allowedFileTypes.Contains(Path.GetExtension(image.FileName))) return false; return true; } }