jquery validation for more than min value

杀马特。学长 韩版系。学妹 提交于 2019-12-21 06:59:51

问题


I am using the jquery validation plugin for form validation. Using the min property works fine, but I want it to validate values strictly greater than that min value.

rules: {
    price: {
        required: true,
        min: 13,
        number: true
    }
}

In my code I have min: 13, but I don't want to allow 13, only values greater than 13, e.g. 13.10, 13.20, 14. How can I do this?

Thanks in advance !


回答1:


Create your own custom method with $.validator.addMethod:

$.validator.addMethod('minStrict', function (value, el, param) {
    return value > param;
});

Then use:

price: {
    required: true,
    minStrict: 13,
    number: true
}

Note: The creators of the validator plugin recommend adding Number.MIN_VALUE to the value you supply:

min: 13 + Number.MIN_VALUE

Number.MIN_VALUE is the smallest positive (non-zero) float that JS can handle, hence the logic is that the two statements below are equivalent:

a > b;
a >= b + Number.MIN_VALUE;

But, this doesn't work, due to the way floating-point numbers are stored in memory. Rounding will cause b + Number.MIN_VALUE to equal b in most cases (b must be very small for this to work).




回答2:


min: 13.01, this:

rules:{ price:{ required: true, min: 13.01, number: true } }



来源:https://stackoverflow.com/questions/6302531/jquery-validation-for-more-than-min-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!