问题
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 ....
<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>
回答1:
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" />
回答2:
$(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" />
回答3:
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;
}
回答4:
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:
Try this example: http://www.codeproject.com/Tips/328178/Allow-only-Numeric-values-in-ASP-Text-box-control
来源:https://stackoverflow.com/questions/27227599/allow-numbers-and-special-characters-only-not-alphabets