Regular expression to accept only numbers and a ","

Asked

Viewed 29,938 times

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.

4 answers

11


First, /\D/g does not take numbers he is the denial of \d that should be the right one to use.

To write more than one condition within a regex you must use |, would look something like:

/\d|,/g

However I think you want to use it to validate broken numbers, so if the value is monetary, you can use it like this:

/^\d+,\d{2}$/

Explaining this regex:

  • As / are used in all regex in javascript everything that goes inside the /.../ are the expressions, all that goes after the second / as g and i are the modifiers
  • ^ indicates that the string should start with any expression that comes after it, in case the \d
  • \d+ indicates that it will look for any number until it finds the next expression which in the case is the ,
  • {2} says the amount of previous characters that should contain
  • $ indicates that the string must end with the characters that come before it.
  • \d{2}$ indicates that it will validate the string if it ends with 2 numeric characters.

Using the ^ along with the $, makes in this case the modified g redundant.

However if you are using with onkeyup it is best to make the mask like this:

/[\d,]/
  • The [...] indicate that the expression can contain any character that is inside these keys.

Extras:

  • g is a modifier that indicates global and serves as "recursiveness", that is to say if you use it like this "ababab".replace(/a/, ""); the mourning will be babab for he removes only the first a what to find, if you do so "ababab".replace(/a/g, ""); will result in this bbb.

  • i indicates case-insensitive (does not differentiate between upper and lower case).

However it is not easy to apply mask with regex, so you can use a jquery pro plugin to work, such as https://github.com/plentz/jquery-maskmoney for example:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="//plentz.github.io/jquery-maskmoney/javascripts/jquery.maskMoney.min.js"></script>

<input type="text" id="meu-input" data-thousands="" data-decimal="," />

<script>
$(function() {
    $('#meu-input').maskMoney();
});
</script>

Read more on: https://en.wikipedia.org/wiki/Regular_expression

  • 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 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.

  • I took your answer and tested, but it didn’t work. I put it in jsfidle. https://jsfiddle.net/gL1uqmbu/

  • @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.

  • The one I use is /[\d\.]+,\d{2}/, for case I have separation in the thousand.

  • 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.

  • @Guilhermelautert Veja found this great example: http://stackoverflow.com/a/16148273/1518921

  • 1

    @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

  • @Guilhermenascimento is this example is even better = D

  • @Guilhermelautert then without wanting to be annoying kk ... this /(\d{1,3}\.?)+,\d{2}/ There’s also a problem, he accepts this 0.100.000,01, at this link /^(?!0+\.00)(?=.{1,9}(\.|$))(?!0(?!\.))\d{1,3}(,\d{3})*(\.\d+)?$/ does not accept to start with 0 because of the ?!0 :) It depends on the need, but I like your example if allowing zero to begin is really quite simple.

Show 5 more comments

1

function soNumeros(numeros)
  { /*Retorna máscara com R$*/
    numeros = numeros.replace(/\D/g, "");
    numeros = numeros.replace(/(\d+)(\d{2})/, "R\$ $1,$2");
    numeros = numeros.replace(/(R\$\s)(\d+)(\d{3})(\,\d{2})/, "$1$2.$3$4");
    numeros = numeros.replace(/(R\$\s)(\d+)(\d{3})(\.\d{3}\,\d{2})/, "$1$2.$3$4");
    numeros = numeros.replace(/(R\$\s)(\d+)(\d{3})(\.\d{3}\.\d{3}\,\d{2})/, "$1$2.$3$4");
    return numeros;  
  }  

You can even do it with one or two lines, but you have to implement a callback in replace, like replace(/expression/, Function(){}). Or create a recursive match expression in type groups:

numero = numero.replace(/(R\$\s)(\d+)(\d{3})((\.\d{3})+\.\d{3}\,\d{2})/, "$1$2.$3$4");
  • did not solve. When I type the letters is validated. But thanks.

0

	/**
	全角数字・全角アルファベットを半角に変換
	Convert zenkaku to hankaku
	ie: japanese number like 012, will be converted to 012.
	*/
	function ZenKakuToHankaku(str) {
		if (str == "") {
			return "";
		}

        //16進数の場合 (0xFEE0 supports hexadecimal)
		return str.replace(/[A-Za-z0-9]/g, function(s) {
			return String.fromCharCode(s.charCodeAt(0) - 0xFEE0);
		});
	}

	/**
	Remove non numeric characters from string.
	Parameter "add" allows to customize the rule. Example, if want allow comma or decimal point.
	*/
	function NumberOnly(str, add) {
	    add = (typeof add === "undefined")? "": add;
		var rule = new RegExp("[^0-9"+add+"]", "g");
		return str.replace(rule, "");
	}

	/**
	Returns only number.
	Before filter the invalid caracters, zenkaku to hankaku sanitization is executed.
	*/
	function NumberFilter(n, add) {
	    add = (typeof add === 'undefined')? '': add;
		n = ZenKakuToHankaku(n);
		if (n == "") {
		    return "";
		}
		n = NumberOnly(n, add);
		return n;
	}

	//console.log("result: "+NumberFilter("9,6", ","));
	//console.log("result: "+NumberOnly("10aaaaaa"));

	function Sanitize() {
		obj = document.getElementById("n");
		obj.value = NumberFilter(obj.value, ",");
	}
<input type="text" size="10" id="n" value="9,6 i y J Ad">
<input type="button" value="sanitize" onclick="Sanitize();">

In this example there is also a sanitization of zenkaku for hankaku.
The zenkaku 全 角 are "full width" characters of the Japanese keyboard.
The hankaku 半 角 are the "half width".

See how they’re different

0123456789
0123456789

Therefore, the function ZenKakuToHankaku() serves to sanitize and allow zenkaku inputs.

The function NumberOnly() removes anything that is not numerical. Therefore, ZenKakuToHankaku() should be applied before.

Another feature other than the other answers is that the function NumberOnly() has a second parameter in which you can implement the regular expression rule. In this case, add the comma character ,. By adding multiple characters or any other like dot ., hyphen -, etc..

This way the routine becomes reusable for different situations.

0

Just remember that HTML5 already includes some kind of field validation.

Examples 1: Interiros enter 100 e 5000

<input type="number" name="n1" min="100" max="5000">

Example 2: numbers with (optionally) two optional boxes:

<input type="text" name="n2" pattern="\d+(,\d\d)?">

Browser other questions tagged

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