Reputation: 883
I use this code for decimal validation.It was working fine.but it allow to enter the alphabets into the text box. when i exit from the text box then only the error message will show nearby textbox.I need,if i press the alphabets the text box doesn't allow to enter the text box , how to do this?
<asp:RegularExpressionValidator ControlToValidate="txtNumber"
runat="server" ValidationExpression="^[1-9]\d*(\.\d+)?$"
ErrorMessage="Please enter only numbers">
</asp:RegularExpressionValidator>
Upvotes: 1
Views: 5735
Reputation: 16144
Using Javascript:
<asp:TextBox ID="TextBox2" onkeypress="AllowOnlyNumeric(event);"
runat="server"></asp:TextBox>
Javascript Code:
function AllowOnlyNumeric(e) {
if (window.event) // IE
{
if (((e.keyCode < 48 || e.keyCode > 57) & e.keyCode != 8) & e.keyCode != 46) {
event.returnValue = false;
return false;
}
}
else { // Fire Fox
if (((e.which < 48 || e.which > 57) & e.which != 8) & e.which != 46) {
e.preventDefault();
return false;
}
}
}
Upvotes: 1
Reputation: 4301
Just use the CompareValidator
, you don't really need to use regex:
<asp:CompareValidator
ID="CompareValidator1" runat="server" ControlToValidate="TextBox1"
ErrorMessage="Please enter a numberical value." ForeColor="Red"
Operator="DataTypeCheck" Type="Integer">!
</asp:CompareValidator>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
You can also do this on the server just using TryParse()
:
int x = 0;
bool valid = Int32.TryParse(TextBox1.Text, out x);
if(!valid)
{
//inform the user
}
Upvotes: 4