Javascript Regex to limit Text Field to only Numbers (Must allow non-printable keys)

前端 未结 6 1938
感情败类
感情败类 2020-12-10 16:46

I have received PHP/JS code from previous developer and I need to add number validation to a Mobile Number field. I already have the HTML validation in place but I need to

6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-10 16:55

    Instead of checking for the event keyCode, why don't you just check for changes inside the actual input and then filter out non-numbers?

    This example uses keyup so that it can read what was actually entered, which means the character is briefly displayed and then removed, but hopefully you get my gist. It might even give the user feedback that the character is not allowed. Either way I think this is the easiest setup, let me know if you need more help fleshing this out.

    function filterNonDigits(evt)
    {
      var event = evt || window.event;
      var val = event.target.value;
      var filtered = val.replace(/[^0-9]/g, '');
    
        if(filtered !== val) {
          event.target.value = filtered;
          event.target.className += " error";
        }
    }
    

    http://jsfiddle.net/mEvSV/1/

    (jquery used solely to easily bind the keyup function, you won't need it for your actual script)

提交回复
热议问题