Regular expression of monetary value

1

Hello, I have the following function

function CarregarMascaras() {
    $('[data-mascara=numeroMonetario]').keyup(function () {
    this.value = this.value.replace(/[^0-9]+[^\,]?[^0-9]+/g, '');
    }).on('paste', function () {
    this.value = this.value.replace(/[^0-9]+[^\,]?[^0-9]+/g, '');
    });
}

The idea of it is as you type, it checks what you have there and maintains it in a format type: N , N . Since N is a quantity of any numbers, but when testing it, it is accepting numbers like N , N , N or N < N . N . I would like this function to accept only numbers of type: N , N .

    
asked by anonymous 25.07.2016 / 22:26

1 answer

1

To remove all but the first commas you can do this:

$('[data-mascara="numeroMonetario"]').on('paste keyup', function() {
    this.value = this.value.split(/[^\d,]/).filter(Boolean).join('');
    var parts = this.value.split(',').filter(Boolean);
    if (parts.length > 1) this.value = [parts.shift()].concat(parts.join('')).join(',');
});

Example: link

What does this code do?

  • joins both events to not repeat the code
  • With this.value = this.value.split(/[^\d,]/).filter(Boolean).join(''); I remove anything other than numbers and commas
  • with var parts = this.value.split(',').filter(Boolean);; part the code in parts separated by commas and clean empty parts
  • [parts.shift()] saves the first part and removes it from parts
  • parts.join('') joins the other parts without commas
  • .join(','); joins the first part with the rest
25.07.2016 / 22:46