Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript function need allow numbers, dot and comma

I need to create a function to allow numbers dot and comma. So anyone corrects the following function

function on(evt) {
  var theEvent = evt || window.event;
  var key = theEvent.keyCode || theEvent.which;
  key = String.fromCharCode( key );
  var regex = /[0-9]|\./;
  if( !regex.test(key) ) {
    theEvent.returnValue = false;
    if(theEvent.preventDefault) theEvent.preventDefault();
  }
}
like image 887
WVW Avatar asked Aug 03 '13 12:08

WVW


3 Answers

Firstly your regex currently doesn't allow comma, which is your requirement.

Secondly, you haven't used any quantifier, so your regex will match only a single character - one of [0-9] or a dot. You need to use a quantifier.

Thirdly, instead of using pipe, you can move all characters inside the character class only.

Try using the below regex:

/^[0-9.,]+$/

Quantifier + is used to match 1 or more occurrence of the pattern.
^ and $ anchors match the beginning, and end of the string respectively.

like image 182
Rohit Jain Avatar answered Nov 19 '22 13:11

Rohit Jain


No need for JavaScript:

<input type="text" pattern="[0-9.,]+" title="Please enter a valid decimal number." />

Modern browsers will handle this perfectly.

If you want to specifically allow commas as thousand separators and a single decimal point, try this:

... pattern="\d{1,2}(,\d{3})*(\.\d+)?" ...

Note that I am firmly against blocking user input. They should be able to type what they want, and then told if they enter something invalid.

like image 44
Niet the Dark Absol Avatar answered Nov 19 '22 11:11

Niet the Dark Absol


Your regex is incorrect.

var regex = /^[0-9.,]+$/;

Regex javascript, why dot and comma are matching for \

https://stackoverflow.com/tags/regex/info

like image 6
HIRA THAKUR Avatar answered Nov 19 '22 13:11

HIRA THAKUR