Validate only numbers

Asked

Viewed 223 times

1

I need to validate a string using Expressão Regular, it can only contain numbers. So I tried using the following expression /[0-9]/, but if the string contain 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 have also tested using the expression /\d/ and the result was the same.

1 answer

4


Try it this way:

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

In that case the answer would be: s = false S10 = false 10 = true 10,0 = false

For floating number is used dot if for example it was used 10.0, 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

Browser other questions tagged

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