Regular expression to accept only numbers and a ","

5

How can I make an expression or function to get only numbers and commas, which the user informs.

I want to get 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 just numbers, but I do not have to get a 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.

    
asked by anonymous 17.10.2015 / 17:48

4 answers

9

First, /\D/g does not take numbers, it is the negation of \d which should be the correct one to use.

To write more than one condition inside a regex you should use | , it 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:

  • The / are used in every regex in the javascript all that goes inside the /.../ are the expressions, everything that goes after the second / as g and i are the modifiers
  • ^ indicates that the string must begin with any expression that comes after it, in this case the \d
  • \d+ indicates that it will search any number until it finds the next expression that in this case is ,
  • {2} tells the number of previous characters it should contain
  • $ indicates that the string should 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 ^ together with $ , in this case makes the modified g redundant.

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

/[\d,]/
  • The [...] indicates that the expression can contain any character within these keys.

Extras:

  • g is a modifier that indicates global and serves as "recursion", ie if you use "ababab".replace(/a/, ""); the result will be babab because it removes only the first a to find, if so "ababab".replace(/a/g, ""); will result in this bbb .

However it is not easy to apply mascara with regex , so you can use a jquery plugin for work, like link 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 at: link

    
17.10.2015 / 18:05
0
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 one or two lines, but you have to implement a callback in replace, type 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");
    
17.10.2015 / 21:55
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 a sanitization of zenkaku to hankaku is also done.
zenkaku 全 角 are full width characters of the Japanese keyboard.
The hankaku 半角 are the "half width".

See how they are different

0123456789
0123456789

Therefore, the ZenKakuToHankaku() function is used to sanitize and allow zenkaku entries.

The NumberOnly() function removes anything other than numeric. Therefore, ZenKakuToHankaku() must be applied before.

Another feature other than the other responses is that the NumberOnly() function has a second parameter in which to implement the regular expression rule. In this case, we add the comma character , . By adding multiple characters or any other such as the point . , hyphen - , etc.

In this way the routine becomes reusable for different situations.

    
01.07.2017 / 20:37
0

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

Example 1: Interviews enter 100 and 5000

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

Example2: numbers with (optionally) two optional boxes:

<input type="text" name="n2" pattern="\d+(,\d\d)?">
    
01.07.2017 / 20:46