javascript 只允许数字和特殊字符,不允许字母

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27227599/
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-10-28 07:11:01  来源:igfitidea点击:

Allow Numbers and Special Characters only not alphabets

javascriptjqueryc#-3.0

提问by Saravana

i have a textbox, in that i want to restrict the alphabets only, that is it will accept only numbers and special charcaters not alphabets..

我有一个文本框,因为我只想限制字母,也就是说它只接受数字和特殊字符而不是字母。

i had tried the below java script ,but it will not working ....

我试过下面的java脚本,但它不起作用......

<script type="text/javascript">
    //Function to allow only numbers to textbox
    function validate(key) {
        //getting key code of pressed key
        var keycode = (key.which) ? key.which : key.keyCode;        
        //comparing pressed keycodes

        if (keyCode >= 65 && keyCode <= 90) {
            return false;
        }       
    } 
    </script>

and in the textbox

并在文本框中

 <asp:TextBox ID="txt1" runat="server" OnTextChanged="txtoldpwd_TextChanged"
                            onkeypress="return validate(event)"></asp:TextBox>

回答by Abhishek Jaiswal

Write script as

将脚本编写为

<script type="text/javascript">
    function Validate(event) {
        var regex = new RegExp("^[0-9-!@#$%*?]");
        var key = String.fromCharCode(event.charCode ? event.which : event.charCode);
        if (!regex.test(key)) {
            event.preventDefault();
            return false;
        }
    }       
</script>

and call like

并打电话给

<asp:TextBox ID="txtcheck" onkeypress="return Validate(event);" runat="server" />

回答by waheed

$(function(){
$('input').keypress(function(e){
var txt = String.fromCharCode(e.which);
console.log(txt + ' : ' + e.which);
if(!txt.match(/[A-Za-z+#.]/))
{
return false;
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text"  />

回答by Srinivas P

function AllowAlphabet(evt) {
 var charCode = (evt.which) ? evt.which : event.keyCode;
 if ((charCode > 64 && charCode < 91) || (charCode > 96 && charCode < 123))
 return true;
 else
return false;
}

回答by Nevin Chaushev

You can use regular expression validator. Here is

您可以使用正则表达式验证器。这是

      <asp:TextBox ID="txt1" runat="server"></asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ControlToValidate="txt1"
    ErrorMessage="Enter a valid number" ValidationExpression="^\d+$"></asp:RegularExpressionValidator>     

Or if you want to use JavaScript:

或者,如果您想使用 JavaScript:

Try this example: http://www.codeproject.com/Tips/328178/Allow-only-Numeric-values-in-ASP-Text-box-control

试试这个例子:http: //www.codeproject.com/Tips/328178/Allow-only-Numeric-values-in-ASP-Text-box-control