HelloWorld1
HelloWorld1

Reputation: 14108

validation of input data

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

Answers (3)

David
David

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

George Johnston
George Johnston

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

Brian Ball
Brian Ball

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

Related Questions