Yvette Yvette - 2 years ago 150
Javascript Question

Validating numeric input and formatting numeric input

I use a function to format larger numbers with commas such as

, thanks to this post:

function numberWithCommas(str) {
return str.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");

The issue is, I have the inputs locked down to accept only numbers with a min value of zero.

<input type="number" min="0" class="myclass" value="@somevalue" />

This poses a problem using the JS, as it needs only number input. Which brings me to a question like this How to make HTML input tag only accept numerical values?, which also offers a JS solution.

I'm wondering if anyone has developed an elegant way to format numeric input display, while validating numeric input, is there are any other options available here?

Answer Source

You can't use the numeric input, because, well, JavaScript doesn't consider formatted number to be a number.

The option is to use the non-numeric input but filter out any "problematic" chars.

In the following example, I'm also handling the dot separator in case you need to accept fractions.

As the text box is being edited, it also has to preserve the cursor position. I've achieved it there with the help of Updating an input's value without losing cursor position.

function format(inp){
  var start = inp.selectionStart,  // get the selection start
      end   = inp.selectionEnd;    // and end, as per the linked post
  var s1=inp.value.split(",").length-1; //count the commas before edit
  var s2=inp.value.split(",").length-s1-1; //count the commas after edit so as to know where to place the cursor, as the position changes, if there are new commas or some commas have been removed
  inp.setSelectionRange(start+s2, end+s2); // set the selection start and end, as per the linked post
function numberWithCommas(str) {
  var a=str.split('.');
  var p=/\B(?=(\d{3})+(?!\d))/g;
    return a[0].toString().replace(p, ",")+"."+a[1];
    return str.toString().replace(p, ",");
<input onkeyup="format(this)">

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download