vishnu reddy
vishnu reddy

Reputation: 123

JavaScript to allow only numbers, comma, dot, backspace

i wrote a javascript function to allow only numbers, comma, dot like this

function isNumber(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();
              }

}

but if i want to remove any number form text box.. backspace is not working. then i changed regex code as "var regex = /^[0-9.,BS]+$/;"

still i am not able to use backspace in textbox.even i cant use left and right keys on textbox is i am doing wrong? can anyone help... thanks. (when I used "BS" in regex instead of backspace its allowing "B","S" Characters in textbox..)

Upvotes: 8

Views: 32216

Answers (4)

Max Ma
Max Ma

Reputation: 1130

React + Typescript + React Hook Form (2024)

<input
  type="text"
  onKeyPress={(e: React.KeyboardEvent<HTMLInputElement>) => {
    const regex = /^[0-9,b]+$/;
    // e.keyCode is deprecated, using e.key
    const result = regex.test(e.key);
    if (!result) return e.preventDefault();
  }}
  {...register(name, {
    shouldUnregister: true,
    onChange(e) {
       /**
        * Side Effects
        * Such as, clear up the previous error state on new input aciton.
        */
    },
    validate(data) {
      /** 
       * Do the further validation...
       * Such as, each number separated by comma should
       * less/greater than cetain numbers 
       */
    }
  })}
/>

this solution helped my for the given tasks of

  • an input can take a sequence of numbers that are separated by a comma, using onKeyPress to handle
  • each number in the sequence should lower than a maximum value, use the validate hook to handle

Upvotes: 0

Jukes
Jukes

Reputation: 437

I have combined a couple of scripts together. For me, I only wanted numbers and one comma.

    $("#TBDepositAmount").keyup(function () {//if a full stop gets through, on keyup, it is changed to a comma
        var val = $(this).val();
        var str = val.replace('.', ',');
        $(this).val(str);
    });

    $("#TBDepositAmount").keydown("keypress keydown blur", function (event) {            

        var key = event.charCode || event.keyCode || 0;
        if ((key == 110 || key == 190) && $(this).val().split(",").length == 1) { //checks whether input is a full stop and lets only 1 through
            return;
        }
        else
            return ( // check if it is a number, only allows numbers through
                key == 8 ||
                key == 9 ||
                key == 13 ||
                key == 46 ||
                (key >= 35 && key <= 40) ||
                (key >= 48 && key <= 57) ||
                (key >= 96 && key <= 105));                           
    });

My input is as follows:

 @Html.TextBoxFor(x => x.deposits.depositAmount, new { @class = "form-control ", autocomplete = "off", id = "TBDepositAmount" })

Upvotes: 1

Hemang Gandhi
Hemang Gandhi

Reputation: 11

Try this code, I modified it and worked for me to allow and comma, dot and digits only.

function isNumber(evt) {
   var theEvent = evt || window.event;
   var key = theEvent.keyCode || theEvent.which;            
   var keyCode = key;
   key = String.fromCharCode(key);          
   if (key.length == 0) return;
   var regex = /^[0-9.,\b]+$/;            
   if(keyCode == 188 || keyCode == 190){
      return;
   }else{
      if (!regex.test(key)) {
         theEvent.returnValue = false;                
         if (theEvent.preventDefault) theEvent.preventDefault();
      }
    }    
 }

Upvotes: 1

anubhava
anubhava

Reputation: 784898

Try this code:

function isNumber(evt) {
          var theEvent = evt || window.event;
          var key = theEvent.keyCode || theEvent.which;
          key = String.fromCharCode(key);
          if (key.length == 0) return;
          var regex = /^[0-9.,\b]+$/;
          if (!regex.test(key)) {
              theEvent.returnValue = false;
              if (theEvent.preventDefault) theEvent.preventDefault();
          }
}

Upvotes: 8

Related Questions