如何在启动时注册客户端验证规则?
How to register client validation rules in startup?
到目前为止我有这个:
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' does not contain a definition for 'Configure' and the best extension method overload 'WebHostBuilderExtensions.Configure(IWebHostBuilder, Action)' requires a receiver of type 'IWebHostBuilder'
您需要配置的选项是 MvcViewOptions 内可访问的 services.AddMvc().AddViewOptions(o => o.ClientModelValidatorProviders.Add(new DateInputValidatorProvider()));
到目前为止我有这个:
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' does not contain a definition for 'Configure' and the best extension method overload 'WebHostBuilderExtensions.Configure(IWebHostBuilder, Action)' requires a receiver of type 'IWebHostBuilder'
您需要配置的选项是 MvcViewOptions 内可访问的 services.AddMvc().AddViewOptions(o => o.ClientModelValidatorProviders.Add(new DateInputValidatorProvider()));