Validation of double using System.Configuration va

2019-05-13 00:42发布

问题:

I had to create a custom configuration section for my library. One of the parameters in the configuration should be positive double. However, for some reason I could not find any Validator for double.

For instance, here's how I use the integer validator:

[ConfigurationProperty("someProp", IsRequired = false, DefaultValue = 15)]
[IntegerValidator(MaxValue = 200, MinValue = 0)]
public int SomeProperty
{
   get
   {
      return (int)this["someProp"];
   }
   set
   {
      this["someProp"] = value;
   }
}

I've looked through Google and was not able to find any mention of DoubleValidator or FloatValidator. Is it possible to somehow make sure the property is a positive double? Are there any reasons DoubleValidator is not present in the System.Configuration? Maybe I am mistaken and double properties should not be stored in the config file.

回答1:

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);
}


回答2:

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 .