Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex replace from number type input

I have a number type input that I want to prevent people from entering anything but numbers. The examples I found work well with input type text fields but don't work well with number fields.

Works well :)

<input type="text" onkeyup="this.value=this.value.replace(/[^\d]/,'')">

Doesn't works well :(

<input type="number" onkeyup="this.value=this.value.replace(/[^\d]/,'')">

Try it for yourself on JSFiddle

Please help...

like image 279
Karl Stulik Avatar asked Apr 30 '14 10:04

Karl Stulik


People also ask

Can you replace with RegEx?

How to use RegEx with . replace in JavaScript. To use RegEx, the first argument of replace will be replaced with regex syntax, for example /regex/ . This syntax serves as a pattern where any parts of the string that match it will be replaced with the new substring.

What is$ 1 in RegEx replace?

For example, the replacement pattern $1 indicates that the matched substring is to be replaced by the first captured group.

How does RegEx replace work?

The REGEXREPLACE( ) function uses a regular expression to find matching patterns in data, and replaces any matching values with a new string. standardizes spacing in character data by replacing one or more spaces between text characters with a single space.

How does RegEx replace work c#?

In a specified input string, replaces a specified maximum number of strings that match a regular expression pattern with a string returned by a MatchEvaluator delegate. In a specified input string, replaces all strings that match a specified regular expression with a string returned by a MatchEvaluator delegate.


1 Answers

I've just done some simple testing using JSFiddle and it would appear that if there is an invalid input on an <input type="number" /> element then the this.value property is returned blank.

The following line showed this result when using Chrome:

<input type="number" oninput="alert(this.value)">

JSFiddle Demo


In fact here's the reason why this happens:

The value attribute, if specified and not empty, must have a value that is a valid floating-point number.

The value sanitization algorithm is as follows: If the value of the element is not a valid floating-point number, then set it to the empty string instead.

^ From the HTML5 Draft Paper section on the implementation of the number input type


This problem has taken my interest now and I've come up with a little workaround.

<input type="number" oninput="updateNum(this)">
function updateNum(e)
{
    e.select();
    e.value = getSelection().toString().replace(/[^\d]/g,'');
}

This has the potential to be buggy if the selection where to change between commands.

JSFiddle for the workaround

like image 174
AeroX Avatar answered Oct 19 '22 14:10

AeroX