I have a class TestClass and I want to customize the validation message instead of default one.
TestClass is the post model in the controller which inherits from ControllerBase.
Here is what I've tried:
TestClass.cs
public class TestClass
{
[TestAtrribute(1.00, 99.99)]
public double TestNumber { get; set; }
}
TestAttribute.cs
public class TestAttribute : ValidationAttribute
{
private double _min;
private double _max;
public TestAttribute(double min, double max)
{
_min = min;
_max = max;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var error = $"{value} is invalid, must be between {_min} and {_max}";
try
{
var convertNum = Convert.ToDouble(value);
if (convertNum < _min || convertNum > _max)
return new ValidationResult(errorMessage);
}
catch (Exception)
{
return new ValidationResult(error);
}
return ValidationResult.Success;
}
}
However, when I post string value, my custom attribute doesn't work. It returns the default message:
Could not convert string to double: test. Path 'TestClass.TestNumber', line 36, position 22.
What I expect is:
test is invalid, must be between 1.00 and 99.99
Please let me know how I can solve it.