I am having a property in my View Model which can accept integer and nullable values:
[Display(Name = \"Code Postal\")]
public int? CodePostal { get; set
The easiest way is to replace default validation resource strings. This other SO answer will help you with that.
But you have to remember that these strings will them be used on all of your models not just particular property of some class.
Note: According to Darin (and me not testing the code) I'm striking part of my answer. The simplified approach by changing resource strings still stands. I've done that myself and I know it works.
Add an additional attribute to your property:
[Display(Name = "Code Postal")]
[RegularExpression("\d+", ErrorMessage = "I'm now all yours...")]
public int? CodePostal { get; set; }
Even though you set regular expression on a non-string property this should still work. If we look at validation code it's like this:
public override bool IsValid(object value)
{
this.SetupRegex();
string text = Convert.ToString(value, CultureInfo.CurrentCulture);
if (string.IsNullOrEmpty(text))
{
return true;
}
Match match = this.Regex.Match(text);
return match.Success && match.Index == 0 && match.Length == text.Length;
}
As we can see, this validator automatically converts the value to string. So if your value is a number it doesn't really matter because it will be converted to a string and validated by your regular expression.