【问题标题】:Validate if an input only contains numeric values - Javascript验证输入是否仅包含数值 - Javascript
【发布时间】:2015-12-11 11:03:49
【问题描述】:

我目前正在使用下面的脚本来获取我的输入并将它们转换为我想要的内容,其中包括一些验证。 我已经设置了服务器端验证,并且还希望有一些客户端,我已经验证了输入的长度,但现在需要确保它们只包含数字。这适用于变量日、月和年。我曾尝试使用 IsNumeric() 但无济于事

<script type="text/javascript">
function timeMachine() {

    var day     = $("#date_day").val();
    var month = $("#date_month").val();
    var year    = $("#date_year").val();

    if (day == "" && month == "" && year != ""){
        if (year.length != 4){
            alert("Please enter a valid year!");
        } else{
            window.location = "/date/" + year ;
        }   
    } else if (day == "" || month == "" || year == ""){
        alert("Please enter a full date!");
    } else{
        var myDate = new Date(year, month-1, day);

        var monthNames = [ "january", "february", "march", "april", "may", "june","july", "august", "september", "october", "november", "december" ];   

        window.location = "/date/" + year + "/" + monthNames[myDate.getMonth()] + "/" + day;
    }
    return false;
}
</script>

想法?

【问题讨论】:

  • 最好使用&lt;input type='date'&gt;

标签: javascript jquery validation


【解决方案1】:

简单的方法,如果您支持现代浏览器,请使用:

<input type="number" />

如果你会使用 JavaScript(和 jQuery),你可以设置一个事件:

$(input).keydown(function (e) {
  if (e.keyCode >= 48 && e.keyCode <= 57) { //0-9 only
    return;
  }
  return false;
});

否则,在最后一级,您可以使用:

/^\d+$/.test(input.value);

【讨论】:

  • 我明白你的意思,但是添加 input type="number" 意味着我的 php 限制长度不再起作用
  • @L.Smith PHP 如何控制你的客户端,你能澄清一下吗?
【解决方案2】:

试试下面的功能:

function isNumber( num ) {
    return ! isNaN( parseFloat( num ) ) && isFinite( num );
}

【讨论】:

    猜你喜欢
    • 2023-03-08
    • 2013-03-02
    • 1970-01-01
    • 2017-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多