I have the following code working
[Required(ErrorMessage = \"Price is required.\")]
[Range(typeof(Decimal), \"1\", \"9999\", ErrorMessage = \"Price xx.xx
I think you may be tripping over a bug in jQuery. That validation is fighting the stuff emitted for your validation attributes.
I have the following property:
[Display(ResourceType = typeof(TaxSetupResources), Name = "Model_Value")]
[RegularExpression(@"(^\d+$)|(^\.\d{1,4}$)|(^\d*\.\d{0,4}$)", ErrorMessageResourceName="Model_InvalidFormatForAmount", ErrorMessageResourceType=typeof(TaxSetupResources))]
public decimal? Value { get; set; }
Used in a view like this:
<div>
@Html.TextBoxFor(t => t.Tiers[i].Value, new { title = @Resources.TaxSetupResources.Model_ValueTip })
<br />@Html.ValidationMessageFor(t => t.Tiers[i].Value)
</div>
Just by itself, a value "foo" yields my error message. A value 0.075 is accepted. A value of .075 yields "The field Value must be a number", the same issue you seem to be having.
based on this SO article, I added the following in document ready:
$(function () {
$.validator.methods.number = function (value, element) {
return parseFloat(value).toString() !== "NaN";
}
});
Now I only get my error message, and only when expected (.075 is accepted).
First off, I think you will want to change your Range attribute to
[Range(typeof(Decimal), "1", "9999", ErrorMessage = "{0} must be a decimal/number between {1} and {2}.")]
According to MSDN, this is the valid way to use RangeAttribute.
Second:
"The field productPrice must be a number."
This is actually unobtrusive client-side JavaScript validation kicking in. Your range validator will fire after the number has been validated. You can disable the number validator although I do not recommend this:
$.validator.methods.number = function (n, t) {
return true;
}
You can try with the regular expression:
[RegularExpression(@"[0-9]*\.?[0-9]+", ErrorMessage = "{0} must be a Number.")]
you can also try the Data Annotations Extensions: http://dataannotationsextensions.org/Home/Wiki
Or write your own implementation,something like this : https://github.com/srkirkland/DataAnnotationsExtensions/blob/master/DataAnnotationsExtensions/DigitsAttribute.cs
UPDATE With REGEX (Matches $9,999.99 | $0.70 | .1)
[RegularExpression(@"^\$?([1-9]{1}[0-9]{0,2}(\,[0-9]{3})*(\.[0-9]{0,2})?|[1-9]{1}[0-9]{0,}(\.[0-9]{0,2})?|0(\.[0-9]{0,2})?|(\.[0-9]{1,2})?)$", ErrorMessage = "{0} must be a Number.")]
Or using Range with a slight modification to @Martin suggestion (actually is a better solution):
[Range(typeof(Decimal), "0", "9999", ErrorMessage = "{0} must be a decimal/number between {1} and {2}.")]