Numeric or Number Only TextBox Using JavaScript or RegularExpressionValidator.
In this example i am going to decsribe how create Numeric or Number only textbox using javascript or regular expression Validator which accept only numbers in asp.net web page.
1. Number only textbox using javascript.
Go to html source of aspx page and write below mentioned script in head section of page.
1
<script type=
"text/javascript"
>
2
function numberOnlyExample()
3
{
4
if
((
event
.keyCode < 48) || (
event
.keyCode > 57))
5
return
false
;
6
}
7
</script>
Call this function in onKeyPress event of textbox.
Write this code in html source of textbox.
<asp:TextBox ID="TextBox2" runat="server" onKeyPress="return numberOnlyExample();"> </asp:TextBox>
We can also do this programmetically in code behind like this.
on Page_Load event of page add onKeyPress attribute to textbox and call the function to accept only numerics.
1
protected
void
Page_Load(
object
sender, EventArgs e)
2
{
3
TextBox2.Attributes.Add(
"onkeypress"
,
"return ((window.event.keyCode >= 48 && window.event.keyCode <= 58))"
);
4
}
HTML Source
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ControlToValidate="TextBox1" ErrorMessage="Please Enter only Numbers" ValidationExpression="\d+"> </asp:RegularExpressionValidator>
Comments
Post a Comment