Javascript 货币验证

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2227370/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 23:20:47  来源:igfitidea点击:

Currency validation

javascriptvalidationexpressioncurrency

提问by dev646

Please help with me writing a JavaScript Validationfor currency/money field.

请帮助我为货币/货币字段编写JavaScript 验证

So please provide any regular expressionsif u have :)

所以请提供任何正则表达式,如果你有 :)

Also, for my region, don't need any currency symbolslike '$' in the field.

此外,对于我所在的地区,字段中不需要任何货币符号,如“$”。

Only decimals are to be included for validation as special chars., along with numbers.

只有小数才能作为特殊字符. 和数字一起包含在验证中

回答by Andy E

You could use a regexp:

您可以使用正则表达式:

var regex  = /^\d+(?:\.\d{0,2})$/;
var numStr = "123.20";
if (regex.test(numStr))
    alert("Number is valid");

If you're not looking to be as strict with the decimal places you might find it easier to use the unary (+) operator to cast to a number to check it's validity:

如果您不希望对小数位如此严格,您可能会发现使用一元 ( +) 运算符更容易转换为数字以检查其有效性:

var numStr = "123.20";
var numNum = +numStr; // gives 123.20

If the number string is invalid, it will return NaN(Not a Number), something you can test for easily:

如果数字字符串无效,它将返回NaN(Not a Number),您可以轻松测试:

var numStr = "ab123c";
var numNum = +numStr;
if (isNaN(numNum))
    alert("numNum is not a number");

It will, of course, allow a user to add more decimal places but you can chop any extra off using number.toFixed(2)to round to 2 decimal places. parseFloatis much less strict with input and will pluck the first number it can find out of a string, as long as that string starts with a number, eg. parseFloat("123abc")would yield 123.

当然,它允许用户添加更多的小数位,但您可以使用number.toFixed(2)四舍五入到小数点后两位。 parseFloat对输入的严格程度要低得多,只要该字符串以数字开头,就会从字符串中提取它可以找到的第一个数字,例如。parseFloat("123abc")会屈服123

回答by Sababado

I built my answer from the accepted answer.

我从接受的答案中构建了我的答案。

var regex = /^[1-9]\d*(((,\d{3}){1})?(\.\d{0,2})?)$/;

var regex = /^[1-9]\d*(((,\d{3}){1})?(\.\d{0,2})?)$/;

^[1-9]The number must start with 1-9
\d*The number can then have any number of any digits
(...)$look at the next group from the end (...)$
(...)?(...)?Look for two groups optionally. The first is for the comma, the second is for the decimal.
(,\d{3}){1}Look for one occurance of a comma followed by exactly three digits
\.\d{0,2}Look for a decimal followed by zero, one, or two digits.

^[1-9]号码必须以 1-9 开头
\d*然后号码可以有任意数量的任意数字
(...)$从末尾开始(...)$
(...)?(...)?查看下一组可选地查找两组。第一个是逗号,第二个是小数点。
(,\d{3}){1}查找逗号后跟三位数字的一次出现
\.\d{0,2}查找小数位后跟零、一位或两位数字。

This regex works off of these rules:

此正则表达式适用于以下规则:

  • Valid values are numbers 0-9, comma and decimal point.
  • If a customer enters more than one decimal point or more than one comma, the value is invalid and will not be accepted.

  • Examples of invalid input values

    • 1.2.3
    • 1,2,4
  • Examples of valid input values
    • 1.23
    • 1,000
    • 3967.
    • 23
    • 1.2
    • 999,999.99
  • 有效值为数字 0-9、逗号和小数点。
  • 如果客户输入多于一位小数点或多于一个逗号,则该值无效,将不被接受。

  • 无效输入值的示例

    • 1.2.3
    • 1,2,4
  • 有效输入值的示例
    • 1.23
    • 1,000
    • 3967。
    • 23
    • 1.2
    • 999,999.99

An example can be seen here: http://jsfiddle.net/rat141312/Jpxu6/1/

一个例子可以在这里看到:http: //jsfiddle.net/rat141312/Jpxu6/1/

UPDATE

更新

by changing the [1-9]in the regex to [0-9]any number less than 1can also be validated. Example: 0.42, 007

通过将[1-9]正则表达式中的 更改为[0-9]小于1也可以验证的任何数字。示例:0.42、007

回答by meouw

/[1-9]\d*(?:\.\d{0,2})?/

[1-9] - must start with 1 to 9
\d* - any number of other digits
(?: )? - non capturing optional group
\. - a decimal point
\d{0,2} - 0 to 2 digits

does that work for you? or maybe parseFloat:

那对你有用吗?或者parseFloat

var float = parseFloat( input );

回答by Jasbeer Rawal

For me its working fine for Indian currency in INR

对我来说,它在 INR 中适用于印度货币

var regex = /^[1-9]{0,2}(,{0,1})(\d{2},)*(\d{3})*(?:\.\d{0,2})$/;
var a = '1,111.11';
regex.test(a); 

回答by user8640104

 let amount = document.querySelector('#amount'), preAmount = amount.value;
        amount.addEventListener('input', function(){
            if(isNaN(Number(amount.value))){
                amount.value = preAmount;
                return;
            }

            let numberAfterDecimal = amount.value.split(".")[1];
            if(numberAfterDecimal && numberAfterDecimal.length > 3){
                amount.value = Number(amount.value).toFixed(3);;
            }
            preAmount = amount.value;
        })
<input type="text" id="amount">