简体   繁体   English

MVC TextBoxFor的输入字段中只有4位数字

[英]Only 4 digit numbers in input field in MVC TextBoxFor

I have an MVC5 project and I have an input field that I only want to take an 8 digit number.我有一个 MVC5 项目,我有一个输入字段,我只想输入一个 8 位数字。 I tried implementing it like this:我尝试像这样实现它:

@Html.TextBoxFor(model => model.oldPin, new { maxlength = "8", @class = "form-control disablecopypaste", onkeydown = "return isNumber(event);" })
 function isNumber(evt) {
        evt = (evt) ? evt : window.event;
        var charCode = (evt.which) ? evt.which : evt.keyCode;

        if (charCode === 16) {
            return false;
        }
        if (charCode > 31 && (charCode < 48 || charCode > 57)) {
            return false;
        }
        return true;
    }

My problem is that while this prevents numbers it allows spaces and special characters.我的问题是,虽然这可以防止数字,但它允许空格和特殊字符。 How do I prevent this?我如何防止这种情况? It works with the keypress event but its depreciated and I'm concerned about browser compatibility.它适用于 keypress 事件,但已贬值,我担心浏览器兼容性。 Is there any way to do this with the keydown event?有没有办法用 keydown 事件做到这一点? All the answers I've seen are all with the keypress event.我看到的所有答案都与按键事件有关。

 function allowNumberOnly (e) { var ascii = (e.which) ? e.which : e.keyCode if (ascii> 31 && (ascii< 48 || ascii> 57)) { return false; } else { var vall = $('#oldPin').val() if (vall.length > 3) { return false; } else { return true; } } }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input class="form-control " id="oldPin" name="oldPin" onkeypress="return allowNumberOnly(event)" type="text" value="">

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM