MVC 4 - DataAnnotations - Validation for Type

前端 未结 3 1999
傲寒
傲寒 2021-02-13 22:43

I have the following code working

    [Required(ErrorMessage = \"Price is required.\")]
    [Range(typeof(Decimal), \"1\", \"9999\", ErrorMessage = \"Price xx.xx         


        
3条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-13 23:01

    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:

    @Html.TextBoxFor(t => t.Tiers[i].Value, new { title = @Resources.TaxSetupResources.Model_ValueTip })
    @Html.ValidationMessageFor(t => t.Tiers[i].Value)

    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).

提交回复
热议问题