Rizwan606
Rizwan606

Reputation: 667

Allow only numeric or decimal data in asp.net textbox

I have a textbox in asp.net in which I want to enter only either numeric or decimal data. The user should not be allowed to even enter any other data. I have tried it myself using the following code. But it does not allow user to enter decimal point for decimal data.

<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>

I had modified the code as below so that it allows the decimal point (period) (code=190)

if (charCode != 190) 
{ ((charCode > 31 && (charCode < 48 || charCode > 57)))
 return false; }
 return true;

But it doesn't work as well (Here i used 190 for period as defined standard). Moreover If someone can help me limit this textbox for user to enter only 6 characters.Can anyone please correct me. I will be really thankful.

Note: I had also tried this. It also works only for numbers and also allows entering of non-numeric data but displays an error message if non-numeric data is entered. But its not what I want. I don't want user to even enter non-numeric data.

<asp:TextBox ID="txtBasicPay" runat="server" Height="15px" Width="120px"></asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" ControlToValidate="txtBasicPay" runat="server" ErrorMessage="Only numbers allowed" ValidationExpression="\d+"></asp:RegularExpressionValidator>

Upvotes: 2

Views: 13638

Answers (2)

Paritosh
Paritosh

Reputation: 2379

Your regex is incorrect , It should be ^\d+$ not \d+.

You might not have hooked up keyup event that is why above one is not working.

But regex will work alone.

Upvotes: 0

haraman
haraman

Reputation: 2752

You can use following as

In ASPX:

<asp:TextBox ID="txtBasicPay" runat="server" Height="15px" Width="120px" onkeypress="return isFloatNumber(this,event);"></asp:TextBox>

Javascript:

function isFloatNumber(e, t) {
   var n;
   var r;
   if (navigator.appName == "Microsoft Internet Explorer" || navigator.appName == "Netscape") {
      n = t.keyCode;
      r = 1;
      if (navigator.appName == "Netscape") {
         n = t.charCode;
         r = 0
      }
   } else {
      n = t.charCode;
      r = 0
   }
   if (r == 1) {
      if (!(n >= 48 && n <= 57 || n == 46)) {
         t.returnValue = false
      }
   } else {
      if (!(n >= 48 && n <= 57 || n == 0 || n == 46)) {
         t.preventDefault()
      }
   }
}

Upvotes: 5

Related Questions