最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

regex - JavaScript to allow only numbers, comma, dot, backspace - Stack Overflow

programmeradmin1浏览0评论

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..)

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..)

Share Improve this question edited Mar 8, 2017 at 18:14 webvitaly 4,2618 gold badges31 silver badges48 bronze badges asked Jan 27, 2014 at 6:49 vishnu reddyvishnu reddy 1231 gold badge5 silver badges9 bronze badges 6
  • I cannot test it, but can you try using the regex /^[0-9.,\b]+$/ instead? – Jerry Commented Jan 27, 2014 at 7:00
  • for backspace its working, thanks. but still I can’t move curser left or right in text box.. – vishnu reddy Commented Jan 27, 2014 at 7:12
  • If you are using jquery, try alphanumeric plugin – Catalin Commented Jan 27, 2014 at 7:13
  • 2 Don't annoy users, you only care what the value is when it's sent to the server. Sniffing keystrokes doesn't check input that is entered via other means. Instead, provide on–screen hints for format, validate input before sending and let users figure it out. – RobG Commented Jan 27, 2014 at 7:14
  • @vishnureddy Ouch, you're also validating that? I don't think you should be using regex to do all this. I'm not that all familiar with JQuery, but what RobG said makes sense. – Jerry Commented Jan 27, 2014 at 7:18
 |  Show 1 more comment

4 Answers 4

Reset to default 8

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

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

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" })

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
发布评论

评论列表(0)

  1. 暂无评论