Search code examples
javascriptjqueryasp.netonbluronkeypress

textbox validation for two numbers and two decimal values in asp.net with javascript


How to check textbox validation for two numbers and two decimal values in asp.net with javascript?

For Example whien i press the key in textbox it should allow me only xx.xx format, example : 12.25, 25.50,48.45 etc.


Solution

  • I got the answer.

    <div>
        <asp:TextBox ID="TextBox2" runat="server" 
             onkeypress="return isDecimalNumber(event,this);" MaxLength="5">
        </asp:TextBox>
    </div>
    
    <script type="text/javascript" language="javascript">
    
      var count = 0;
      function isDecimalNumber(evt, c) {
          count = count + 1;
          var charCode = (evt.which) ? evt.which : event.keyCode;
          var dot1 = c.value.indexOf('.');
          var dot2 = c.value.lastIndexOf('.');
          if (count > 2 && dot1 == -1) {
              c.value = "";
              count = 0;
          }
          if (dot1 > 2) {
              c.value = "";
          }
          if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57))
              return false;
          else if (charCode == 46 && (dot1 == dot2) && dot1 != -1 && dot2 != -1)
              return false;
    
          return true;
      }
    </script>