[英]Model Validation from Unit Testing only works for string
I have got a class like this 我有这样的课
Model: 模型:
public class Circle
{
[Required(ErrorMessage = "Diameter is required")]
public int Diameter { get; set; }
[Required(ErrorMessage = "Name is required")]
public string Color { get; set; }
}
Testing: 测试:
[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);
}
I was expecting it'd fail whenever Diameter or Color is null. 我原本以为Diameter或Color为null时都会失败。 However, the above testing only failed when the string parameter, Color, is null.
但是,上述测试仅在字符串参数Color为空时失败。 Why?
为什么? How should I do in order to validate Diameter as well?
我也应该怎么做才能验证直径?
You shouldn't use the Required attribute with numeric properties. 您不应将Required属性与数字属性一起使用。 Use the Range attribute instead:
改用Range属性:
The RequiredAttribute attribute specifies that when a field on a form is validated, the field must contain a value.
RequiredAttribute属性指定在验证表单上的字段时,该字段必须包含一个值。 A validation exception is raised if the property is null, contains an empty string (""), or contains only white-space characters.
如果属性为null,包含空字符串(“”)或仅包含空格字符,则会引发验证异常。
RequiredAttribute only validates against null (and empty strings), but an int is non-nullable and becomes 0 by default. RequiredAttribute仅针对null(和空字符串)进行验证,但是int不可为null,默认情况下变为0。
You could make it nullable (with int?
) or you could use a different kind of attribute. 您可以将其设置为可空值(使用
int?
),也可以使用其他类型的属性。 As DmitryG says, you could use the RangeAttribute if there's a certain range of numbers that are acceptable to you, but if not I think the only way would be a CustomValidationAttribute with a function to compare the value to zero. 正如DmitryG所说,如果在一定范围内可接受的数字范围内,则可以使用RangeAttribute,但如果不行,我认为唯一的方法是将CustomValidationAttribute与一个将值与零进行比较的函数。
EDIT: Given that it's a diameter, I guess you need to make sure it's positive, and not just unequal to zero. 编辑:鉴于这是一个直径,我想您需要确保它为正数,而不仅仅是不等于零。 In this case a RangeAttribute may indeed be best, with 1 as the minimum and
Int32.MaxValue
as the maximum. 在这种情况下,RangeAttribute可能确实是最好的,最小值为1,最大值为
Int32.MaxValue
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.