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

前端 未结 6 1949
感情败类
感情败类 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 17:20

    The best method here is to use input event which handles all your concerns. It is supported in all modern browsers. With jQuery you can do like following. Handles all cases pasting the value with mouse/keyboard backspace etc.

    $('.numeric').on('input', function (event) { 
        this.value = this.value.replace(/[^0-9]/g, '');
    });
    

    See it here

    You can check if input event is supported by checking if the input has this property if not you can use onkeyup for older browsers.

    if (inputElement.hasOwnProperty('oninput')) {
        // bind input
    } else {
        // bind onkeyup
    }
    

提交回复
热议问题