代码之家  ›  专栏  ›  技术社区  ›  Andrew Simpson

如何在启动时注册客户端验证规则?

  •  0
  • Andrew Simpson  · 技术社区  · 6 年前

    public class DateInputValidator : IClientModelValidator
    {
        public void AddValidation(ClientModelValidationContext context)
        {
            context.Attributes["data-val"] = "true";
            context.Attributes["data-val-custom"] = "Error message";
            this.GetErrorMessage(context);
        }
    
        private string GetErrorMessage(ClientModelValidationContext context)
        {
            return $"{context.ModelMetadata.GetDisplayName()} is not a valid youtube url";
        }
    }
    
    public class DateInputValidatorProvider : IClientModelValidatorProvider
    {
        public void CreateValidators(ClientValidatorProviderContext context)
        {
            if (context.ModelMetadata.ModelType == typeof(string) &&
                context.ModelMetadata.DataTypeName == "DateInputType" &&
                !context.Results.Any(m => m.Validator is DateInputValidator))
            {
                context.Results.Add(new ClientValidatorItem
                {
                    Validator = new DateInputValidator(),
                    IsReusable = true
                });
            }
        }
    }
    

    我试图通过我在网上找到的例子来注册:

    在startUp.cs中

    public void ConfigureServices(IServiceCollection services)
    {
        services.Configure(o =>
        o.ClientModelValidatorProviders.Add(new DateInputValidatorProvider()));
    }
    

    “IServiceCollection”不包含“Configure”的定义和最佳扩展方法重载“WebHostBuilderExtensions.Configure(IWebHostBuilder,Action)”需要“IWebHostBuilder”类型的接收器

    1 回复  |  直到 6 年前
        1
  •  2
  •   Maverik    6 年前

    您需要配置的选项是 MvcViewOptions 可进入内部 services.AddMvc().AddViewOptions(o => o.ClientModelValidatorProviders.Add(new DateInputValidatorProvider()));

    推荐文章