javascript validate if the number contains +/-

2

I have a problem, I have a function that makes a debit in the database, but if the User changes the amount by placing arithmetic operators the value becomes negative, thus crediting credits to the user instead of discounting.

How can I validate not to allow the input of +/- and also validate the value of the variable in the same way.

My debit function

function debitashop(valor){
    getCreditosPlayer(function(output) {
        var creditosplayer  = output;
        creditosplayer = parseFloat(creditosplayer);
        valor = valor.val(valor.replace(/[^\w]/gi, ''));
        valor = parseFloat(valor);

        valor = (creditosplayer - valor);
        $.ajax({
            url:  "ajax/debita.php",
            type: "POST",
            data: "creditos="+valor,
            success: function(dados){
                getCreditosPlayer(function(output) {});
            }
        })
    });
}
    
asked by anonymous 02.11.2016 / 00:35

1 answer

3

I solved the problem as follows

First I converted the value to string. (in the case of the function)

valor = String(valor);

Then I removed what are not numbers

valor = valor.replace(/[^0-9\.]+/g, "");

In the case of input, I did the same thing on the onkeyup event

    
02.11.2016 / 01:44