简体   繁体   中英

How to customize validation message for model?

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.

Please override FormatErrorMessage method:

    public override string FormatErrorMessage(string name)
    {
        return $"{name} is invalid, must be between {_min} and {_max}";
    }

Difficult to say as I don't see line numbers and I'm not sure when exception is thrown. But you may to use TryParse instead of throwing exception and catching then.

int result;

if (double.TryParse(custBal.Text, out result))
{

            if (result< _min || result> _max)                
                return new ValidationResult(errorMessage); 
}
else
{
            return new ValidationResult(error);

}

As per my understanding, I believe you have developed a WebApi and trying to pass data using PostMan. The error you have posted is rejected by.Net framework because of its type safety feature. Since you are passing 'string' instead of 'double'.

Considering, you are accepting data for model 'TestClass' using 'FormBody' or by passing any JSON or XML string object.

The best way is to Validate the input data by an if condition before assigning it to the Model 'TestClass'. If it contains string then your custom message.

Hope this will solve your query.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM