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);​
2
  • I suppose [this article][1] [1]: stackoverflow.com/questions/18082/… will help you. Commented Mar 29, 2012 at 4:57
  • thanks .. also it should allow only digits not any other alphabets or special characters Commented Mar 29, 2012 at 5:06

3 Answers 3

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'/>
Sign up to request clarification or add additional context in comments.

2 Comments

IMO W3Schools is a horrible site, that frequently gives examples using worst practices (see w3fools.com). There's an equivalent page on MDN (generally a much better source of information) - developer.mozilla.org/en-US/docs/HTML/Element/Input. Good answer though, +1
Ohh I never realized and always considered it a reliable source. Thanks for pointing out. I have removed the reference from the answer.
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

Comments

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

      }
    }

2 Comments

you modified your question till i submitted my answer. but still you customize this and use.
thanks pranav.. would like to hav validation in textbox with allowing only digits

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.