Search code examples
c#validationasp.net-corecustom-validatorsasp.net-boilerplate

Check for existing record in ICustomValidate of ASP.NET Boilerplate


For ICustomValidate in ASP.NET Boilerplate, we can validate the value for the field.

I am wondering whether it is able and recommended to check whether the added name of the Student already exists, in the ICustomValidate.

For example, when creating a new student, we will check whether the student with the same name already exists. Can we move this logic to ICustomValidate?


Solution

  • You can:

    public class CreateStudentDto : ICustomValidate
    {
        public string Name { get; set; }
    
        public void AddValidationErrors(CustomValidationContext context)
        {
            using (var scope = context.IocResolver.CreateScope())
            {
                using (var uow = scope.Resolve<IUnitOfWorkManager>().Begin())
                {
                    var studentRepository = scope.Resolve<IRepository<Student, long>>();
    
                    var nameExists = studentRepository.GetAll()
                        .Where(s => s.Name == Name)
                        .Any();
    
                    if (nameExists)
                    {
                        var key = "A student with the same name already exists";
                        var errorMessage = context.Localize("sourceName", key);
                        var memberNames = new[] { nameof(Name) };
                        context.Results.Add(new ValidationResult(errorMessage, memberNames));
                    }
    
                    uow.Complete();
                }
            }
        }
    }
    

    But such validation is usually done in a domain manager, e.g. AbpUserManager

    Custom Validation in the DTO would be recommended for invariant conditions:

    public class CreateTaskInput : ICustomValidate
    {
        public int? AssignedPersonId { get; set; }
    
        public bool SendEmailToAssignedPerson { get; set; }
    
        public void AddValidationErrors(CustomValidatationContext context)
        {
            if (SendEmailToAssignedPerson && (!AssignedPersonId.HasValue || AssignedPersonId.Value <= 0))
            {
                var errorMessage = "AssignedPersonId must be set if SendEmailToAssignedPerson is true!";
                context.Results.Add(new ValidationResult(errorMessage));
            }
        }
    }