JSFiddle - React, Tailwind, and code Playground

by gregborbonus

HTML

<input type="text" id="test" maxlength="14" name="test" onkeypress="return isNumber(event,this)" />

JavaScript

function isNumber(event,el) {
    event = (event) ? event : window.event;
    
    var charCode = (event.which) ? event.which : event.keyCode;
  
	  if (charCode > 31 && (charCode < 48 || charCode > 57)) {
        return false;
    }
    //Add a space after 4 numbers.


    var v=el.value + String.fromCharCode(charCode); //Keypress does not let us see the value of the text box after the press, so we have to add the string to our comparison.
    v=v.replace(/\s/g,'');

    el.value=v.replace(/(.{4})/g, '$1 ').trim(); // using regex from other answer. Thanks @Gops AB for the example
    return false;
}