validation of input data
Goal: Validate input data in my e-formulary.
Question: What syntax code (da开发者_如何学运维taannotations) do I need to ensure that data is int or decimal?
The default model binder should handle validation automatically if you have specified your properties as int or decimal. You should get the following validation error if an incorrect value is entered:
public class MyObject
{
public int MyProperty { get; set; }
}
The value 'i am a string' is invalid for MyProperty.
If you would like to do further validation such as only allowing certain ranges or formatting then you could use the RangeAttribute or the RegularExpressionAttribute attributes.
[RegularExpression(@"\d+", ErrorMessage="MyProperty must be an int.")]
public int MyProperty { get; set; }
[Range(typeof(Decimal), "20", "25")]
public decimal MyProperty { get; set; }
If you are recieving your data from an input box, you can use a TryParse
on your data. e.g.
decimal dec;
if(decimal.TryParse(YourInput.Text, out dec))
{
// Valid Decimal
}
else { // Invalid }
...Same goes for an int, with int.TryParse()
;
Maybe I'm not understanding the question. For data type validation, simply have the property on your model be of the desired type (int or decimal).
精彩评论