Introduction
Just a simple textbox control which allows only integer input using client-side JavaScript code. It also provides a property of type int
so that setting and getting the value of the control is made much easier.
Using the code
Using NumericTextBox
is as simple as using the built-in TextBox
control. The value of NumericTextBox
can be changed either at design time through the Designer or at runtime through code.
<body>
<form id="form1" runat="server">
<cc1:NumericTextbox ID="NumericTextbox1"
runat="server" Value="76">76</cc1:NumericTextbox>
</form>
</body>
The NumericTextBox
control provides a public property for getting or setting its integer value:
[Description ("The integer value of the NumericTextBox")]
public int Value
{
get
{
int ret;
if (!int.TryParse(Text,out ret))
return 0;
return ret;
}
set { Text = value.ToString(); }
}
Let's see what happens on the prerender
event of NumericTextBox
:
protected override void OnPreRender(EventArgs e)
{
string scriptName = "ValidationScript";
if (!Page.ClientScript.IsClientScriptBlockRegistered(scriptName))
Page.ClientScript.RegisterClientScriptBlock(Page.GetType(),
scriptName,
"<script language="\""javascript\">" +
" function IsNumeric(e,elem) {" +
" var currentText = elem.value; " +
" if(window.event)" +
" {" +
" keynum = e.keyCode;" +
" }" +
" else if(e.which)" +
" {" +
" keynum = e.which;" +
" }" +
" return (keynum >= 48 && keynum <= 57) " +
" || (keynum == 45 && currentText == '') " +
" || (keynum == 8) || (keynum == 127); " +
" } </script>");
Attributes.Add("onKeyPress", "return IsNumeric(event,this)");
base.OnPreRender(e);
}
As we see in the above code, the handling of the KeyPress
event is assigned to a client-side JavaScript function named IsNumeric()
. This function returns true
if the key pressed was a valid numeric key and false
otherwise. So any invalid key press is ignored.
Because of the different ways the various browsers handle the keypress
event, the value of the key pressed is assigned to a local variable keynum
in a different way depending on the browser used. So, if the browser being used is Internet Explorer, the value is taken from the keyCode
property of the event object; otherwise the value is taken from the 'which
' property of the event object.
The function returns true
on the following circumstances:
- The key pressed was a numeric key (0-9), having a key number from 48 (the key number of zero) to 57 (the key number of nine)
- The key pressed was the minus sign (-) , only if it is the first character of the input text of the textbox
- The key pressed was the delete key (key number 8)
- The key pressed was the backspace key (key number 127)
Conclusion
This is just a simple custom control mostly inspired by various JavaScript codes implementing numeric validation available on the Internet. Future improvements could be decimal number support and overflow/underflow check.
Thanks for reading!