2

I'm working on an ASP.NET web project using VS2010/C#, I have some text boxes which users should enter only numbers in them, how can I prevent users from entering non-numeric, floating point numbers and negative numbers in my text boxes? of course I can check entered numbers in server side code, but I think sending data to server and performing validation will take a huge amount of time, is there a way to prevent users from entering non-numeric values? or at least not sending data to server with incorrect data?

thanks

Ali_dotNet
  • 3,219
  • 10
  • 64
  • 115
  • Its too late to do it serverside (the user already tried typing something). You can easily do it with jQuery - look here http://stackoverflow.com/questions/995183/how-to-allow-only-numeric-0-9-in-html-inputbox-using-jquery – Marco Johannesen Oct 14 '11 at 06:25

2 Answers2

2

Simply use some javascript and apply to the text box required, then it will not allow the others except numbers, see the following code part.

 <script language="JavaScript">
function onlyNumbers(evt)
{
    var e = event || evt; // for trans-browser compatibility
    var charCode = e.which || e.keyCode;

    if (charCode > 31 && (charCode < 48 || charCode > 57))
        return false;

    return true;

}
</script>

EDIT:

<asp:textbox id="txtNOD" runat="server" Width="52px" Font-Size="10px" 
 Font-Names="Verdana" Height="16px" Enabled="False" onkeypress="return onlyNumbers();"></asp:textbox>
  • thanks but how can I apply this javascript on my text box? where should I call it? – Ali_dotNet Oct 14 '11 at 06:57
  • 1
    @Ali_dotNet , see the Edited Code for that – Sai Kalyan Kumar Akshinthala Oct 14 '11 at 07:01
  • Hi @SaiKalyanKumarAkshinthala. Can you please tell me how can I update the code to allow period (.) as well. I have tried the following but it doesn't work. Thanks ----------------------------------------- if (charCode != 190) { ((charCode > 31 && (charCode < 48 || charCode > 57))) return false; } return true; – Rizwan606 Oct 11 '15 at 04:32
1

You can use ASP.NET validation controls or write JavaScript to handle text/key events or even better try out jQuery or pluging to validate user input.

KV Prajapati
  • 93,659
  • 19
  • 148
  • 186