1

How to prevent or validate the user entering numbers 6 digits with range (eg: 100000) and two decimal digits in a textbox using javascript ? I m using onkeypress event in my textbox my code is:

      var txtBudget = document.getElementById('MainContent_txtBudget');
        txtBudget.addEventListener('keypress', function (evt)
        {  
        var value = this.value + String.fromCharCode(evt.which);
        if (!/^\d{0,6}(?:\.\d{0,2})?$/.test(value)) 
           {   
             evt.preventDefault();
           }
       },
 false);​
Pranav
  • 8,563
  • 4
  • 26
  • 42
kk1076
  • 1,740
  • 13
  • 45
  • 76

3 Answers3

2

With HTML5 input type='number' there is no need to use javascript for this validation. Say for example you want a number between 100,000.00 and 200,000 with two decimal digits, use this in your HTML

Number: <input type="number" name="number" min="100000.00" max="200000" step='0.01'/>
Juzer Ali
  • 4,109
  • 3
  • 35
  • 62
  • IMO W3Schools is a horrible site, that frequently gives examples using worst practices (see http://w3fools.com/). There's an equivalent page on MDN (generally a much better source of information) - https://developer.mozilla.org/en-US/docs/HTML/Element/Input. Good answer though, +1 – Rich O'Kelly Apr 19 '13 at 15:35
  • Ohh I never realized and always considered it a reliable source. Thanks for pointing out. I have removed the reference from the answer. – Juzer Ali Apr 19 '13 at 21:24
1

I wonder why not to use RegularExpression control from Asp.net toolbox. Check out this sample:

<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" ControlToValidate="TextBox1"
 runat="server" ValidationExpression="^\d{1,6}(\.\d{1,2})?$" ErrorMessage="Only 6 digit numbers allowed"></asp:RegularExpressionValidator>

And if my ValidationExpression is wrong visit this link for your choice: Find Any Regular Expression

Ashwini Verma
  • 7,477
  • 6
  • 36
  • 56
0

'i guess you want something like this , call this function onKeyPress Event of your textbox

 function test()
    {
      var obj=document.getElementById('textbox1');
      if(obj.value)
      {
            if(isNaN(obj.value)) 
            {
               alert('Please enter only numbers');
                return;
            }

      }
    }
Pranav
  • 8,563
  • 4
  • 26
  • 42