user3865601
user3865601

Reputation: 39

Asp.net How to limit number of digits before and after the decimal point in textbox keypress event

I have a Gridview with a textbox. How do I limit the number of digits before and after the decimal point in a textbox keypress event? I want a maximum of 6 digits before the decimal point and 2 digits after the decimal point. How do I do this with javascript/JQuery?

Upvotes: 2

Views: 4166

Answers (2)

Win
Win

Reputation: 62260

I personally do not like wiping out the data as soon as a user types something.

Instead, I like to display an error message after they finish entering data.

For example,

<asp:TextBox runat="server" ID="TextBox1" MaxLength="9" />
<asp:RegularExpressionValidator runat="server" ID="RegularExpressionValidator1"
    ValidationExpression="^((\d{5})*|([1-9]\d{0,5}))(\.\d{0,2})?$"
    ControlToValidate="TextBox1" Text="Input must be 123456.78 format." 
    Display="Dynamic" />

Upvotes: 2

invernomuto
invernomuto

Reputation: 10211

Most simple javascript validation vanilla style check

http://jsfiddle.net/InferOn/8aCJc/

HTML

    <input type="text" id="myInput" onkeyup="check()" />

Javascript

 function check() {
  var check = true;
  var txt = document.getElementById('myInput');
  tmp = txt.value;
  if (tmp && tmp.length > 0) {

    arg = tmp.split('.');
    if (arg && arg.length > 0) {

      check = arg[0].length <= 6;
      if (arg.length > 1 && check) {
        check = arg[1].length <= 2;
      }
    }


  }
  if (!check)
    alert('check failed');

}

Upvotes: 1

Related Questions