我有一个文本框,因为我只想限制字母,也就是说它只接受数字和特殊字符而不是字母..
我曾尝试过以下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>
并在文本框中
<asp:TextBox ID="txt1" runat="server" OnTextChanged="txtoldpwd_TextChanged"
onkeypress="return validate(event)"></asp:TextBox>
答案 0 :(得分:1)
将脚本编写为
<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>
并调用
<asp:TextBox ID="txtcheck" onkeypress="return Validate(event);" runat="server" />
答案 1 :(得分:1)
$(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" />
答案 2 :(得分:0)
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;
}
答案 3 :(得分:-1)
您可以使用正则表达式验证程序。这是
<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>
或者如果您想使用JavaScript:
试试这个例子: http://www.codeproject.com/Tips/328178/Allow-only-Numeric-values-in-ASP-Text-box-control