Pregunta

Utilizo Ninject, MVC4, Automapper y FluentValidation pegados.

He escrito un validador para mi modelo de vista y he escrito un validador reutilizable que debe invocarse dentro del validador del modelo de vista.

El problema es que cuando publico el formulario, la anulación Validate no se llama en el validador del modelo de vista, por lo que el validador reutilizable tampoco se llama, por lo que al final el ModelResult es válido ... (causando una excepción al escribir la entidad al DB) ...

Lo extraño es que cuando agregué una regla para una de las propiedades, la forma se valida bien.

public class RequiredSourceViewModelValidator : AbstractValidator<RequiredSourceViewModel>
    {
        public RequiredSourceViewModelValidator()
        {
            Mapper.CreateMap<RequiredSourceViewModel, Source>();
        }

        public override FluentValidation.Results.ValidationResult Validate(RequiredSourceViewModel requiredSourceViewModel)
        {
            var validator = new SourceValidator();

            var source = Mapper.Map<RequiredSourceViewModel, Source>(requiredSourceViewModel);

            return validator.Validate(source);
        }
    }


public class SourceValidator : AbstractValidator<Source>
    {
        public SourceValidator()
        {
            RuleFor(s => s.Name)
                .NotEmpty()
                    .WithMessage("Naam mag niet leeg zijn.")
                .Length(1, 100)
                    .WithMessage("Naam mag niet langer zijn dan 100 karakters.");

            RuleFor(s => s.Url)
                .NotEmpty()
                    .WithMessage("Url mag niet leeg zijn.")
                 .Must(BeAValidUrl)
                    .WithMessage("Url is niet geldig.")
                .Length(1, 100)
                    .WithMessage("Url mag niet langer zijn dan 100 karakters.");
        }

        private bool BeAValidUrl(string url)
        {
            if (url == null)
            {
                return true;
            }

            var regex = new Regex(@"^http(s)?://([\w-]+.)+[\w-]+(/[\w- ./?%&=])?$");
            return regex.IsMatch(url);
        }
    }

public class Source : IEntity
    {
        /// <summary>
        /// Gets or sets the primary key of the source.
        /// </summary>
        public int Id { get; set; }

        /// <summary>
        /// Gets or sets the name of the source.
        /// </summary>
        public string Name { get; set; }

        /// <summary>
        /// Gets or sets the url of the source.
        /// </summary>
        public string Url { get; set; }

        /// <summary>
        /// Gets or sets the ordinal of the source.
        /// </summary>
        /// <value>
        /// The ordinal of the source.
        /// </value>
        public int Ordinal { get; set; }

        public int? GameId { get; set; }
    }

¿Qué podría estar mal aquí?

¿Fue útil?

Solución

Estás anulando la sobrecarga incorrecta. Necesita anular el método Validar con la firma: public virtual ValidationResult Validate(ValidationContext<T> context) porque este método se llamará durante la validación de MVC:

public override ValidationResult Validate(
      ValidationContext<RequiredSourceViewModel> context)
{
     var validator = new SourceValidator();

     var source = 
         Mapper.Map<RequiredSourceViewModel, Source>(context.InstanceToValidate);

     return validator.Validate(source);
 }

La otra sobrecarga solo se usa si llama manualmente valide como validator.Validate(object).

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top