how to restrict user to enter only numbers in textbox using javascript and how to restrict user to enter only 10 digits(mobile number) in textbox using javascript or how to restrict user to enter only alphanumeric in textbox using javascript
Introduction
Here
I will explain how to restrict user to allow only numbers in textbox
and how to restrict user to enter only 10 digits mobile number using
JavaScript and I will explain how to allow only numbers and alphabets in
textbox using JavaScript.
Description
I
have a one textbox now I need to allow user to enter only numbers not
more than that if user try to enter characters or alphabets I don’t want
to allow those characters in textbox for that I have written one
JavaScript function to allow only numbers and allow only 10 numbers.
To implement this you need to write below code in your aspx page
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Allow Only Numbers and alpahabates Page</title>
<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;
var phn = document.getElementById('txtPhn');
//comparing pressed keycodes
if (!(keycode==8 || keycode==46)&&(keycode < 48 || keycode > 57))
{
return false;
}
else
{
//Condition to check textbox contains ten numbers or not
if (phn.value.length <10)
{
return true;
}
else
{
return false;
}
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txtPhn" runat="server" onkeypress="return validate(event)"></asp:TextBox>
</div>
</form>
</body>
</html>
|
Demo
Please enter text in below textbox
|
After that here we will see how to restrict user to
enter only alphanumeric in textbox
To implement this you need to write below code in your aspx page
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Allow Only Numbers and alpahabates Page</title>
<script type="text/javascript">
//Function to allow only alpha
numeric to textbox
function validatealphanumeric(key) {
var keycode = (key.which) ? key.which : key.keyCode
var phn = document.getElementById('txtChar');
//comparing pressed keycodes
if (!(keycode==8 || keycode==46)&&(keycode < 48 || keycode > 57) && (keycode
< 97 || keycode > 122)) {
return false;
}
else {
return true;
}
}
</script>
</head>
<body>
<form id="form1"
runat="server">
<div>
<asp:TextBox ID="txtname"
runat="server"
onkeypress="return
validatealphanumeric(event)"></asp:TextBox>
</div>
</form>
</body>
</html>
No comments:
Post a Comment