Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class CreateUserCommand : IRequest<ItemResponse<UserType>>
- {
- public CreateUserCommand(UserType user)
- {
- User = user;
- }
- public UserType User { get; }
- public class Validator : AbstractValidator<CreateUserCommand>
- {
- public Validator(UserValidator userValidator)
- {
- CascadeMode = CascadeMode.StopOnFirstFailure;
- RuleFor(x => x.User)
- .NotNull()
- .SetValidator(userValidator, UserValidator.OnCreateRules)
- .OverridePropertyName(string.Empty);
- }
- }
- }
- public class UserValidator : AbstractValidator<UserType>
- {
- private const string OnCreate = nameof(OnCreate);
- private const string OnUpdate = nameof(OnUpdate);
- public UserValidator(IUserRepository userRepository)
- {
- RuleFor(x => x.Email)
- .NotEmpty()
- .EmailAddress()
- .OverridePropertyName("email");
- RuleSet(OnCreate, () =>
- {
- RuleFor(x => x.Email)
- .MustAsync(async (email, cancel) =>
- {
- var tryGetUserByEmail = await userRepository.TryGetUserByEmail(email, cancel);
- return tryGetUserByEmail == null;
- })
- .WithMessage("User with email '{PropertyValue}' already exists")
- .OverridePropertyName("email");
- });
- RuleSet(OnUpdate, () =>
- {
- RuleFor(x => x.Email)
- .MustAsync(async (user, email, cancel) =>
- {
- var existing = await userRepository.TryGetUserByEmail(email, cancel);
- return existing == null || user.Id == existing.Id;
- })
- .WithMessage("User with the same email already exists")
- .OverridePropertyName("email");
- });
- }
- public static string[] OnCreateRules => new[] {"default", OnCreate};
- public static string[] OnUpdateRules => new[] {"default", OnUpdate};
- }
Advertisement
Add Comment
Please, Sign In to add comment