2011-01-21 130 views
0

目标: 验证我的电子公式中的输入数据。验证输入数据

问题: 我需要什么语法代码(dataannotations)来确保数据是int还是decimal?

回答

0

如果从一个输入框recieving你的数据,你可以使用你的数据TryParse。例如

decimal dec; 
if(decimal.TryParse(YourInput.Text, out dec)) 
{ 
    // Valid Decimal 
} 
else { // Invalid } 

...同样适用于int,其中int.TryParse();

0

也许我不理解这个问题。对于数据类型验证,只需将模型中的属性设置为所需的类型(int或decimal)即可。

1

如果您已将属性指定为int或decimal,则默认模型联编程序应自动处理验证。如果输入了不正确的值是你应该得到以下验证错误:

public class MyObject 
{ 
    public int MyProperty { get; set; } 
} 

The value 'i am a string' is invalid for MyProperty. 

如果你想这样做进一步验证,如只允许在一定范围或格式,那么你可以使用RangeAttributeRegularExpressionAttribute属性。

[RegularExpression(@"\d+", ErrorMessage="MyProperty must be an int.")] 
public int MyProperty { get; set; } 

[Range(typeof(Decimal), "20", "25")] 
public decimal MyProperty { get; set; } 
+0

您也可以使用带有整数的`RangeAttribute`。 http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.rangeattribute.aspx – Oded 2011-01-21 17:58:49