7
How can I make an expression or function to pick only numbers and comma, which the user informs.
I want to pick up a product pricing form. If the user types a letter or something other than the comma, it will not be validated. I have the example with only numbers, but I don’t have to pick comma:
javascript:
function soNumeros(numeros) { //variavel do parametro recebe o caractere digitado//
return numeros.replace(/\D/g,"");
}
Form:
<label="soNumeros">
Só números: <input id="numeros" onkeypress="mascara(this, soNumeros)" maxlength="11"/>
</label>
Then just call the function in the form using onkeypress.
What does the "/" symbol mean? And the ""? I wonder why you have the two symbols together. What does "$" mean? Boy, I’ve thought about studying javascript, but it’s a bit complex.
– André Nascimento
@Andrénascimento your question was about a regex specifies and not about learning regex, however I edited the answer so you have an idea of where to start.
– Guilherme Nascimento
I took your answer and tested, but it didn’t work. I put it in jsfidle. https://jsfiddle.net/gL1uqmbu/
– André Nascimento
@Andrénascimento did not work because there are errors in the syntax and already charged in the console, outside that its variables are not defined, I will edit the answer. Outside a "very" important detail, you html and javascript all together in the fiddle within the javascript field.
– Guilherme Nascimento
The one I use is
/[\d\.]+,\d{2}/
, for case I have separation in the thousand.– Guilherme Lautert
Good evening @Guilhermelautert, xará ... the thousand case you showed even works, but it accepts random values as
1.1.1,00
, maybe use?
get more precision, I do not know yet for sure because I am rusty in regex.– Guilherme Nascimento
@Guilhermelautert Veja found this great example: http://stackoverflow.com/a/16148273/1518921
– Guilherme Nascimento
@Guilhermenascimento I understand, the one I commented is a simpler version and as you demonstrate not exact, but this contemplates
/(\d{1,3}\.?)+,\d{2}/
either in the regex101– Guilherme Lautert
@Guilhermenascimento is this example is even better = D
– Guilherme Lautert
@Guilhermelautert then without wanting to be annoying kk ... this
/(\d{1,3}\.?)+,\d{2}/
There’s also a problem, he accepts this0.100.000,01
, at this link/^(?!0+\.00)(?=.{1,9}(\.|$))(?!0(?!\.))\d{1,3}(,\d{3})*(\.\d+)?$/
does not accept to start with0
because of the?!0
:) It depends on the need, but I like your example if allowing zero to begin is really quite simple.– Guilherme Nascimento