javascript validate if the number contains +/-

Asked

Viewed 407 times

2

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

how can I validate to not allow entering +/- and also validate the variable value in the same way.

my function that makes the debt

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) {});
            }
        })
    });
}
  • You want to validate whether the operator is in the middle of the input or just ignore it?

  • I want to be not allowed to enter operator, if type give replace pr ''

  • Insert the following after line 3: creditosplayer = creditosplayer.replace(/[ w]/gi, '');

  • in the case of the variable value ? it is this that I need to validate

  • would be that /[ 0-9. ]+/g, ""

  • To accept only numbers yes

  • Post the answer and approve to someone who has a similar question posteiormently

  • 1

    done, thanks for the help ^^

Show 4 more comments

1 answer

3


I solved the problem as follows

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

valor = String(valor);

Then I took out what are not numbers

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

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

  • You could just use \d, getting .replace(/[^\d]/g, '').

  • 1

    If you’re doing this to prevent abuse, you need to do it on the server side as well.

  • Still thinking about it, I’ll have to do in php too

  • @Sergio what changes leaving d, sorry ignorance but I do not understand well

  • Place 0-9 or only \d is the same, \d means "number"

  • is if it’s 50.50 then it’ll pass as 5050 right ?

  • @Sergio can tell me how it would look in php with preg_replace ?

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.