Range DataAnnotation Doesn't Seem to Be Working in .Net 3.5

流过昼夜 提交于 2020-01-06 04:20:42

问题


Using .Net 3.5

I have a Range Attributes (System.ComponentModel.DataAnnotations) on a Property...

   [Range(0, 5, ErrorMessage = "Weight must be between 0 and 5")]
    public virtual double Weight{ get; set; }

And I have a Validate method in the class that checks validation attributes...

protected virtual void Validate()
{
    var type = this.GetType();
    foreach (var property in type.GetProperties())
    {
        foreach (ValidationAttribute attribute in 
            property.GetCustomAttributes(typeof(ValidationAttribute),true))
        {
            if(!attribute.IsValid(property.GetValue(this, null)))
            {
                BrokenRules.Add(attribute.ErrorMessage);
            }
        }
    }
}

    public virtual bool IsValid()
    {
        return GetBrokenRules().Count == 0;
    }

And I have an NUnit test that tests the validation...

[TestCase(-.1, Result = false)] // fails
[TestCase(0.0, Result = true)]
[TestCase(5.0, Result = true)]
[TestCase(5.1, Result = false)]  // fails
public bool ItValidatesWeight(double weight)
{
    _ornament.Weight = weight;
    return _ornament.IsValid();
}

Required attributes are working properly but on the class and test correctly, but the Range attributes are not. Any suggestions?


回答1:


It was interpreting the attribute as using the int overload.

It worked with:

[Range(0.0, 5.0, ErrorMessage = "Weight must be between 0 and 5")]
    public virtual double Weight{ get; set; }


来源:https://stackoverflow.com/questions/3480140/range-dataannotation-doesnt-seem-to-be-working-in-net-3-5

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