Validation of double using System.Configuration validator

时间秒杀一切 提交于 2019-12-05 18:57:45
Morten Toudahl

I needed a float validator for my own project, and found your question. This is how I made my validator. When/if you use it, you should remember to set a default value on the ConfigurationPropertyAttribute that you annotate the property with.

Thanks to Kasper Videbæk for finding my mistake: ConfigurationValidatorBase validate method receives default value

class DoubleValidator : ConfigurationValidatorBase
{
    public double MinValue { get; private set; }
    public double MaxValue { get; private set; }

    public DoubleValidator(double minValue, double maxValue)
    {
        MinValue = minValue;
        MaxValue = maxValue;
    }

    public override bool CanValidate(Type type)
    {
        return type == typeof(double);
    }

    public override void Validate(object obj)
    {
        double value;
        try
        {
            value = Convert.ToDouble(obj);
        }
        catch (Exception)
        {
            throw new ArgumentException();
        }

        if (value < MinValue)
        {
            throw new ConfigurationErrorsException($"Value too low, minimum value allowed: {MinValue}");
        }

        if (value > MaxValue)
        {
            throw new ConfigurationErrorsException($"Value too high, maximum value allowed: {MaxValue}");
        }
    }
}

The attribute to use on the configurationproperty

class DoubleValidatorAttribute : ConfigurationValidatorAttribute
{
    public double MinValue { get; set; }
    public double MaxValue { get; set; }

    public DoubleValidatorAttribute(double minValue, double maxValue)
    {
        MinValue = minValue;
        MaxValue = maxValue;
    }

    public override ConfigurationValidatorBase ValidatorInstance => new DoubleValidator(MinValue, MaxValue);
}
OscuroAA

You could try RangeValidator. Something like

[Range(0,double.MaxValue, ErrorMessage = "Number must be positive. ")]
public float someProperty (...) { ...}

You can see this SO answer for more examples https://stackoverflow.com/a/17164247 .

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!