Search code examples
c#asp.net-core-2.0custom-validators

How to register client validation rules in startup?


So far I have this:

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

and I am trying to register via the example I found on the web:

In startUp.cs

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

but get the error:

'IServiceCollection' does not contain a definition for 'Configure' and the best extension method overload 'WebHostBuilderExtensions.Configure(IWebHostBuilder, Action)' requires a receiver of type 'IWebHostBuilder'


Solution

  • The options you need to configure are the MvcViewOptions accessible inside services.AddMvc().AddViewOptions(o => o.ClientModelValidatorProviders.Add(new DateInputValidatorProvider()));