Click here to Skip to main content
15,908,581 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I want to apply multiple data annotation on a property named Year.

Following is my code:
[Required(Error Message="Year is Required")]
[Range(1900, 2050, ErrorMessage = "Enter the Valid Year")]
public string Year

When i enter an invalid year then it is working fine but when i do not enter any year in the textbox , it is again showing the Range error but the expected error message is :"Year is Required".

Please Help..

1 solution

From the few code you have posted, it is difficult to know exactly where the error comes. As I can see your "Year" is a String, so you are probably converting it to int when entered, so you can validate with your range.

Some possiblities that I can imagine:
- If the string is empty, the conversion to number might return a error code that you anyways evaluate and it is out of your range
- The variable you are using to hold the converted "year" is already having a value (probably 0), when the conversion of the string is not successful, the variable remains with initialized value, and that value is out of your range triggering the wrong error message.

Since you are not giving more information about your code, it is difficult to know where the error is.

Please have a look to[^]. It might give you a possible approach to (at least) have a better error handling
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900