Here's a simple validation attribute I wrote to enforce number-only strings (I use it to validate phone numbers, postal codes and alike):
public class NumericAttribute : ValidationAttribute {
public NumericAttribute() {
ErrorMessage = SharedModelResources.ValidationStrings.Numeric; // Message coming from a .resx file
}
public override bool IsValid(object value) {
string stringValue = value as string;
if (stringValue.IsNotNull())
foreach (var c in stringValue)
if (!char.IsDigit(c))
return false;
return true;
}
}
The problem is that when used to validate other than strings, let's say a decimal, short, int or anything else, object value
is ALWAYS null
. Why validate numeric only decimals? Because if I don't, I get the default validation message 'The value 'x' is not valid for 'propertyName'. I'm aware of the solutions for the specific problem of the default validation message.
I just want to understand WHY it's always null...
BTW, I'm using VS2008, ASP.NET MVC 2 (final), .NET 3.5 SP1.
Ok, thanks @mcl for suggesting debugging all the way down (View > Controller > Model) to the validation attribute!
Here's what happened: when inserting invalid input in a textbox binded to anything that's not a string in the model, the ´DefaultModelBinder´ sets it's value to ´null´ before it reaches even the controller! (Anyone have more info on that? I would be glad!)