Reputation: 14108
Goal: Validate input data in my e-formulary.
Question: What syntax code (dataannotations) do I need to ensure that data is int or decimal?
Upvotes: 0
Views: 232
Reputation: 15360
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; }
Upvotes: 1
Reputation: 32278
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()
;
Upvotes: 0
Reputation: 12606
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).
Upvotes: 0