I get the validation message "The value xxx is not valid for yyy". It happens when I post incorrect value for double type. I have no idea how to change it.
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
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);
}
}
回答2:
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);