I found an ugly workaround.
It seems that if category_id is a nullable int?
and my value is not a valid number, a null value is passed, and the model doesn't see the invalid 'abc' value.
[Range(0, 999999, ErrorMessage = "category_id must be a valid number")]
public int? category_id { get; set; }
// when we pass a good number
MyAction?category_id=123
validation: successful
// when we pass a bad number
// validation ignores it. not what we want.
MyAction?category_id=abc
validation: successful
If I change category_id to a non-nullable int
, it fails validation even when no value is passed.
[Range(0, 999999, ErrorMessage = "category_id must be a valid number")]
public int? category_id { get; set; }
// when we pass a good number
MyAction?category_id=123
validation: successful
// when we pass an bad number
MyAction?category_id=abc
validation: "category_id must be a valid number"
// BUT, when we don't pass any number at all ...
MyAction
validation: "category_id must be a valid number"
The Ugly Workaround
If I change category_id to a string
, and then only convert it to an int
when I need it, I can validate it properly, using only [Range]
[Range(0, 999999, ErrorMessage = "category_id must be a valid number")]
public string category_id { get; set; }
// when we pass a good number
MyAction?category_id=123
validation: successful
// when we pass a bad number
MyAction?category_id=abc
validation: "category_id must be a valid number"
// no number, no validation. hooray!
MyAction
validation: successful
It's ugly, but it works.
(Note: the custom attribute was not needed, so I removed it and just used [Range])
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…