DataAnnotation with custom ResourceProvider

后端 未结 3 1582
有刺的猬
有刺的猬 2020-12-28 16:43

I have created a custom ResourceProvider to pull localization information from a database. I now want to use DataAnnotation to add

3条回答
  •  感动是毒
    2020-12-28 17:13

    I have used fluent validation to achieve this. It saves me lots of time. This is what my Globalized validator looks like. It does mean that you don't use data anotations, but sometimes data anotations get a bit big and messy.

    Here is an example:

    (Errors.Required, Labels.Email and Errors.AlreadyRegistered are in my blobal resources folder.)

    public class CreateEmployerValidator : AbstractValidator {
        public RegisterUserValidator() { 
            RuleFor(m => m.Email)
                .NotEmpty()
                .WithMessage(String.Format(Errors.Required, new object[] { Labels.Email }))
                .EmailAddress()
                .WithMessage(String.Format(Errors.Invalid, new object[] { Labels.Email }))
                .Must(this.BeUniqueEmail)
                .WithMessage(String.Format(Errors.AlreadyRegistered,  new object[] { Labels.Email }));
        }
    
        public bool BeUniqueEmail(this IValidator validator, string email )  {
            //Database request to check if email already there?
            ...
        }    
    }
    

    Like I said, it is a move away form data annotations, only because I already have too many annotations on my methods already!

提交回复
热议问题