Skip to content

Instantly share code, notes, and snippets.

@jonhilt
Created July 1, 2020 13:11
Show Gist options
  • Save jonhilt/7065d5fa2f5967702d7733e24f3c77d9 to your computer and use it in GitHub Desktop.
Save jonhilt/7065d5fa2f5967702d7733e24f3c77d9 to your computer and use it in GitHub Desktop.
public class CommandValidator : AbstractValidator<Command>
{
private ApplicationDbContext _dbContext;
public CommandValidator(ApplicationDbContext dbContext)
{
_dbContext = dbContext;
RuleFor(c => c.Body).NotEmpty();
RuleFor(c => c.Slug).NotEmpty()
.Matches("^[a-z0-9]+(?:-[a-z0-9]+)*$")
.WithMessage("Please enter a valid slug, using only alphanumeric characters and hyphens e.g. test-post")
.Must(BeUniqueSlug).WithMessage("Slug already in use, try a different one");
RuleFor(c => c.Title).NotEmpty();
}
private bool BeUniqueSlug(string slug)
{
return _dbContext.Posts.Count(x => x.Slug == slug) == 0;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment