Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override default ASP.NET MVC message in FluentValidation

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.

like image 577
SiberianGuy Avatar asked Sep 14 '11 06:09

SiberianGuy


1 Answers

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);
   }
}
like image 187
Jeremy Skinner Avatar answered Nov 09 '22 08:11

Jeremy Skinner