开发者

Override default ASP.NET MVC message in FluentValidation

I get the validation message "The value xxx i开发者_StackOverflows not valid for yyy". It happens when I post incorrect value for double type. I have no idea how to change it.


Unfortunately this isn't something that FluentValidation has the ability to override - the extensibility model for MVC's validation is somewhat limited in many places, and I've not been able to find a way to override this particular message.

An alternative approach you could use is to define two properties on your view model - one as a string, and one as a nullable double. You would use the string property for MVC binding purposes, and the double property would perform a conversion (if it can). You can then use this for validation:

public class FooModel {
   public string Foo { get; set; }

   public double? ConvertedFoo {
      get {
          double d;
          if(double.TryParse(Foo, out d)) {
             return d;
          }
          return null;
      }
   }
}


public class FooValidator : AbstractValidator<FooModel> {
   public FooValidator() {
      RuleFor(x => x.ConvertedFoo).NotNull();
      RuleFor(x => x.ConvertedFoo).GreaterThan(0).When(x => x.ConvertedFoo != null);
   }
}


You could use the .WithMessage() method to customize the error message:

RuleFor(x => x.Foo)
    .NotEmpty()
    .WithMessage("Put your custom message here");

and if you want to use localized messages with resources:

RuleFor(x => x.Foo)
    .NotEmpty()
    .WithLocalizedMessage(() => MyLocalizedMessage.FooRequired);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜