jquery 中的简单数字验证输入

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18101551/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 21:00:50  来源:igfitidea点击:

simple numeric validation in jquery for input

jqueryvalidationnumeric

提问by Ganesh

can anyone help me for simple jquery numeric validation?

任何人都可以帮助我进行简单的 jquery 数字验证吗?

<input type="text" name="yourphone" id="yourphone" required style="border-radius:6px; border:1px solid #ccc; width:300px; height:25px;" />
<input type="submit" value="Send Inquiry" class="button" id="mySubmitButton" />

回答by Sergio

You can change your input type to number like <input type="number"...(although not all browsers support HTML5 input types).

您可以将输入类型更改为类似数字<input type="number"...(尽管并非所有浏览器都支持 HTML5 输入类型)。

Oryou can use this:

或者你可以使用这个:

$('#myform').on('submit', function(){
    var value = $('#yourphone').val()
    return $.isNumeric(value);
});

but phone numbers can be complex, not just numbers.

但电话号码可能很复杂,而不仅仅是数字。

In casethe user uses +()-.,you can use this:
(demo)

如果用户使用+()-.,您可以使用此:
演示

$('#myform').on('submit', function(){
    var value = $('#yourphone').val()
    var regex = new RegExp(/^\+?[0-9(),.-]+$/);
    if(value.match(regex)) {return true;}
    return false;
});

回答by jajama

$('#myform').on('submit', function(){

    var value = $('#yourphone').val()
    var regex = new RegExp(/^\+?[0-9(),.-]+$/);
    if(value.match(regex)) {return true;}
    return false;
});

回答by Breen ho

<script type="text/javascript">
    var specialKeys = new Array();
    specialKeys.push(8); //Backspace
    $(function () {
        $(".numeric").bind("keypress", function (e) {
            var keyCode = e.which ? e.which : e.keyCode
            var ret = ((keyCode >= 48 && keyCode <= 57) || specialKeys.indexOf(keyCode) != -1);
            $(".error").css("display", ret ? "none" : "inline");
            return ret;
        });
        $(".numeric").bind("paste", function (e) {
            return false;
        });
        $(".numeric").bind("drop", function (e) {
            return false;
        });
    });
</script>