validate decimal numbers

孤街醉人 提交于 2019-12-03 22:41:57

Based on the examples here:

$.validator.addMethod('Decimal', function(value, element) {
    return this.optional(element) || /^\d+(\.\d{0,3})?$/.test(value); 
}, "Please enter a correct number, format xxxx.xxx");

or with commas permitted:

$.validator.addMethod('Decimal', function(value, element) {
    return this.optional(element) || /^[0-9,]+(\.\d{0,3})?$/.test(value); 
}, "Please enter a correct number, format xxxx.xxx");

To prevent that the number can't have decimals, you could use the following:

// This will allow numbers with numbers and commas but not any decimal part
// Note, there are not any assurances that the commas are going to 
// be placed in valid locations; 23,45,333 would be accepted

/^[0-9,]+$/

To require always having decimals, you would remove the ? which makes it optional and also require that the digit character (\d) be 1 to 3 digits long:

/^[0-9,]+\.\d{1,3}$/

This is interpreted as match the beginning of the string (^) followed by one or more digits or comma characters. (The + character means one or more.)

Then match the . (dot) character which needed to be escaped with a backslash (\) due to '.' normally meaning one of anything.

Then match a digit but only 1-3 of them. Then the end of the string has to appear. ($)

Regular expressions are very powerful and great to learn. In general they will benefit you no matter what language you run into in the future. There are lots of great tutorials online and books you can get on the subject. Happy learning!

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