验证欧元字符串货币

时间:2018-03-15 09:23:39

标签: javascript regex

我想验证文本字段中的用户输入是欧元的有效金额。

示例:

100,00 //valid
100,123123 //valid
100.000,21 //valid
100000 //valid

10.00.00 //invalid
100,000,000 //invalid

以逗号分隔的小数,整数的可选点。

我设法接近我想要的东西

static validateEuro = value => {
  const pattern = /^\d+(?:,?\d+)$/;
  return pattern.test(`${value}`);
}

**但是如果正确放置点,则无法验证,例如** 100.000.000

试验:



  it('Values without comma or dot are valid integers', () => {
    expect(AmountInput.validateEuro('100')).toBeTruthy();
    expect(AmountInput.validateEuro(1000)).toBeTruthy();
  });

  it('Values with a single comma are valid', () => {
    expect(AmountInput.validateEuro('100,00')).toBeTruthy();
    expect(AmountInput.validateEuro('100,131')).toBeTruthy();
  });

  it('Values with more than a comma are invalid', () => {
    expect(AmountInput.validateEuro('100,000,000')).toBeFalsy();
  });

  it('Values with wrong placed dots should be invalid', () => {
    expect(AmountInput.validateEuro('10.00.00')).toBeFalsy();
  });

  it('Values with correct placed dots should be valid', () => {
    expect(AmountInput.validateEuro('100.000.000')).toBeTruthy();
  });

  it('Values with characters should be invalid', () => {
    expect(AmountInput.validateEuro('asda10')).toBeFalsy();
  });




任何帮助都将受到高度赞赏

3 个答案:

答案 0 :(得分:0)

您可以使用RegEx ^(\d)+(,\d+)?$|^(\d{3}\.?)+(,\d+)?$

在本RegEx中,我将编号的情况与dots分开。

^(\d)+(,\d+)?$匹配没有点的数字

  • (\d)+至少匹配一次数字

  • (,\d+)?匹配,[at least one digit]一次或零次

^(\d{3}\.?)+(,\d+)?$将数字与点匹配

  • (\d{3}\.?)+至少匹配一次序列[digit][digit][digit].?

  • (,\d+)?匹配,[at least one digit]一次或零次

<强> Demo

答案 1 :(得分:0)

我建议following regex:

^(\d+|\d{1,3}(\.\d{3})*)(,\d+)?$

让我们解读一下:

^                              $  # match complete line
 (\d+|\d{1,3}(\.\d{3})*)          # match the part before the comma
     |                            # match either:
  \d+                             # a sequence of digits
      \d{1,3}(\.\d{3})*           # or this, which is:
      \d{1,3}                     # up to three digits, followed by
             (\.\d{3})*           # a dot, and three digits, 0 or more times
                        (,\d+)?   # match the part after the comma, if it exists 
                         ,\d+     # a comma, followed by at least one digit

答案 2 :(得分:0)

您可以使用以下正则表达式:

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

if (regex.test(value))
{
    var twoDecimalPlaces = /\,\d{2}$/g;
    var oneDecimalPlace = /\,\d{1}$/g;
    var noDecimalPlacesWithDecimal = /\,\d{0}$/g;

    if(value.match(twoDecimalPlaces ))
    {
        return value;
    }
    if(value.match(noDecimalPlacesWithDecimal))
    {
        return value+'00';
    }
    if(value.match(oneDecimalPlace ))
    {
        return value+'0';
    }
    return value+",00";
}
return null;
};