长度的fluentvalidtion客户端错误消息不显示

时间:2017-12-21 09:44:48

标签: asp.net-mvc validation fluentvalidation

我使用FluentValidation来验证LoginViewModel,就像这样

public class LoginViewModelValidator : AbstractValidator<LoginViewModel>
    {
        public LoginViewModelValidator()
        {
            RuleFor(l => l.Password).NotEmpty().WithMessage("非空").Length(5, 100);
            RuleFor(l => l.UserName).NotEmpty().Length(5, 100).WithMessage("'{PropertyName}' 必须是 {MaxLength} 个字符,您已经输入了 {TotalLength} 字符。");
            RuleFor(l => l.Code).NotEmpty().MaximumLength(4);
        }
    }

当我输入太长或太短的密码时,我收到的错误信息是在jquery.validate中:

  

请输入5到100个字符之间的值。

我认为这应该显示FluentValidation的默认错误消息。 具有WithMessage的用户名的错误消息,如此

  

'用户名'必须是100个字符,您已经输入了{TotalLength}字符。

{TotalLength}出现了

MaximumLength和MinimumLength它们都有同样的问题。 其他人工作正常

Golbal.cs:

protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            FluentValidationModelValidatorProvider.Configure();
        }

我所说的所有错误信息都是在提交之前,Js验证结果。

1 个答案:

答案 0 :(得分:0)

我无法解决你的问题,请你为它提供一个简单的项目。

这是我的解决方案。

public class Customer
{
    public int Id { get; set; }
    public string Surname { get; set; }
    public string Forename { get; set; }
    public decimal Discount { get; set; }
    public string Address { get; set; }
}
public class CustomerValidator : AbstractValidator<Customer>
{
    public CustomerValidator()
    {
        RuleFor(customer => customer.Surname).NotNull().Length(5, 20).
            WithMessage("'{PropertyName}' 必须是 {MaxLength} 个字符,您已经输入了 {TotalLength} 字符。");
    }
}



    public class HomeController : Controller
{

    public ActionResult About()
    {
        var customer = new Customer
        {
            Surname = "韩非子"
        };
        CustomerValidator validator = new CustomerValidator();
        var results = validator.Validate(customer);

        return View();
    }
}

你应该看到如下图所示的结果。

Running