문제

나는 Ninject, MVC4, Automapper 및 FluentValidation을 함께 사용합니다.

내보기 모델에 대한 유효성 검사기를 작성했으며 View Model Validator 내에서 호출 해야하는 재사용 가능한 유효성 검사기를 작성했습니다.

문제는 양식을 게시 할 때 Validate Override가 View Model Validator에서 호출되지 않으므로 재사용 가능한 유효성 검사기도 호출되지 않으므로 결국 ModelResult가 유효합니다 ... (엔티티를 작성할 때 예외가 발생합니다. DB에 ... ...

이상한 점은 속성 중 하나에 대한 규칙을 추가했을 때 양식이 잘 검증되고 있다는 것입니다.

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; }
    }

여기서 무엇이 잘못되었을 수 있습니까?

도움이 되었습니까?

해결책

당신은 잘못된 과부하를 무시하고 있습니다. 서명으로 Validate 메소드를 재정의해야합니다. public virtual ValidationResult Validate(ValidationContext<T> context) 이 방법은 MVC 검증 중에 호출됩니다.

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

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

     return validator.Validate(source);
 }

다른 과부하는 수동으로 Validate를 호출하는 경우에만 사용됩니다. validator.Validate(object).

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top