Validate numbers only

0

I need to validate a string using Expressão Regular , it can only contain numbers. So I tried to use the following expression /[0-9]/ , but if the string contains a character and a number is considered valid.

er = new RegExp(/[0-9]/);

document.getElementById("retorno").innerHTML = "" +
"s = " + Boolean(er.exec("s")) + "<br>" +
"s10 = " + Boolean(er.exec("s10")) + "<br>" +
"10 = " + Boolean(er.exec("10")) + "<br>" +
"10,0 = " + Boolean(er.exec("10,0")) + "<br>";
<div id="retorno"></div>

NOTE: I also tried using the expression /\d/ and the result was the same.

    
asked by anonymous 14.01.2018 / 19:26

1 answer

3

Try this:

var valor = new RegExp('^[0-9]+$');

In this case the answer would be this: s = false s10 = false 10 = true 10.0 = false

For floating numbers a dot is used if for example 10.0 was used, you can use this way:

var valor = new RegExp(/^-?\d*\.?\d*$/);

You have the following result:

s = false s10 = false 10 = true 10.0 = true

    
14.01.2018 / 19:38