2014-09-10 42 views
1

我有这样的模型验证只适用于字符串

模型类:

public class Circle 
{ 
    [Required(ErrorMessage = "Diameter is required")] 
    public int Diameter { get; set; } 

    [Required(ErrorMessage = "Name is required")] 
    public string Color { get; set; } 
} 

测试:

[TestMethod] 
public void TestCircle() 
{ 
    Circle circle = new Circle(); 
    circle.Diameter = 5; 
    circle.Color = "Black"; 
    ValidationContext contex = new ValidationContext(circle, null, null); 
    Validator.ValidateObject(circle , contex); 
} 

我期待它会失败,只要直径或者颜色为空。但是,上述测试仅在字符串参数Color为空时失败。为什么?我应该怎么做才能验证Diameter?

+0

我猜猜它是因为int不可为空并且默认为0,因此在这种情况下有效。不完全确定。如果在你的圈子类中使用int(nullable int),会发生什么? – hschne 2014-09-10 14:30:35

+1

'int'默认为0,如果你想测试'null'你必须使用'int?'。此外,我认为你想写'circle.Diameter'而不是'Circle.Diameter',因为'Diameter'不是'静态的' – glautrou 2014-09-10 14:48:58

+0

这很有道理,谢谢大家! – ydoow 2014-09-10 14:59:28

回答

2

您不应将Required属性与数字属性一起使用。使用Range属性改为:

的RequiredAttribute标签属性指定当窗体 在现场验证,该字段必须包含一个值。如果属性为空,包含空字符串(“”),则会引发验证异常 ,或者 仅包含空格字符。

2

RequiredAttribute只针对null(和空字符串)进行验证,但int是不可空的,默认为0。

您可以使其为空(使用int?)或者您可以使用其他类型的属性。正如DmitryG所说,如果有一定范围的数字可以接受,那么可以使用RangeAttribute,但如果不是,我认为唯一的方法是使用函数将该值与零比较的CustomValidationAttribute。

编辑:鉴于它是一个直径,我想你需要确保它是正面的,而不仅仅是不等于零。在这种情况下,RangeAttribute的确可能是最好的,最低为1,最高为Int32.MaxValue

相关问题