locked
Restrict User to enter the Numbers up to 10. RRS feed

  • Question

  • User-1824994464 posted

    Hi,

    I have a commission field in one of my Web Form. I wrote a script to allow only numbers in that field. Please see below my script.

    Now i want the user to enter the numbers or float only up to 10. i shouldn't allow the user to enter the number > 10. Can you guys help me with this. 

    Thanks

        function NumberAndFloat(event, field) {
    
            if (navigator.appName == "Microsoft Internet Explorer") {
                var val = document.getElementById(field).value;
                var Key = window.event.keyCode;
                if ((Key >= 48 && Key <= 57) || (Key == 46 && val.indexOf(".") == -1)) {
                    return true;
                }
                else {
                    return false;
                }
            }
            else {
                var val = document.getElementById(field).value;
                var Key = event.which;
                if (Key == 8) {
                    return true;
                }
                else if (Key == 0) {
                    return true;
                }
                else if ((Key >= 48 && Key <= 57) || (Key == 46 && val.indexOf(".") == -1)) {
                    return true;
                }
                else {
                    return false;
                }
    
            }
        }

    Wednesday, March 26, 2014 7:51 PM

Answers

  • User281315223 posted

    I apologize for some of the additional responses as they aren't really related to your issue.

    Consider the first example using the autonumeric plug-in that I provided, which using MVC might look like :

    <!DOCTYPE html>
    <html>
    <head>
      <meta charset="utf-8">
      <title>JS Bin</title>
      <!-- jQuery and Plugin References -->
      <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
      <script src="http://www.decorplanit.com/plugin/autoNumeric-1.9.18.js"></script>
      <script type='text/javascript'>
        $(function($) {
          // Defines your numeric masking for any elements with the class numericOnly and sets the maximum to 10
          $('.numericOnly').autoNumeric('init', { vMax: 10.00 });    
        });  
      </script>
    </head>
    <body>
      <!-- Define your specific properties for your field -->
      @Html.TextBoxFor(f => f.MarketInfo.Agency.Other_CashCommission, new { @class = "input numericonly" })
    </body>
    </html>

    A plugin is likely a better choice simply because it will not only perform better in a cross-browser sense, but its likely going to be much more reliable and well tested than one that you elect to write yourself.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, March 27, 2014 12:53 PM

All replies

  • User281315223 posted

    Recommendation : Use a Plug-in

    There are a few approaches that you can use to handle this but the easiest might be to consider using an actual plug-in like autoNumeric to handle this, which might look like the following to implement :

    <!DOCTYPE html>
    <html>
    <head>
      <meta charset="utf-8">
      <title>JS Bin</title>
      <!-- jQuery and Plugin References -->
      <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
      <script src="http://www.decorplanit.com/plugin/autoNumeric-1.9.18.js"></script>
      <script type='text/javascript'>
        $(function($) {
          // Defines your numeric masking for any elements with the class numericOnly and sets the maximum to 10
          $('.numericOnly').autoNumeric('init', { vMax: 10.00 });    
        });  
      </script>
    </head>
    <body>
      <!-- Define your specific properties for your field -->
      <input type="text" class="numericOnly" >
    </body>
    </html>

    It has a wide variety of support for different currencies, minimum / maximum values and formatting rules and should be able to handle anything that you would need when it comes to dealing with currency (or numeric input in general). It's just something to consider if you are going to be delving into jQuery-based options, as there is no need to re-invent logic that has already been done and likely rigorously tested.

    Other Approaches (which may only apply to integers)

    Limiting the Length

    For instance, the MaxLength attribute available on a TextBox or the maxlength attribute <input> element can help limit the number of character that could be entered within it : 

    <!-- Examples using the MaxLength (ASP.NET) or maxlength (HTML) options -->
    <asp:TextBox ID="YourTextBox" runat="server" MaxLength="10"></asp:TextBox>
    <input maxlength='10' />

    Restricting Characters

    There are multiple approaches to limiting the characters that can be entered into a TextBox. You could consider capturing the available keycode each time that a key is pressed and determining if you want to allow that event to occur or not :

    <!-- Establish a Key Press event to determine if you want to allow this specific character to be pressed -->
    <asp:TextBox ID="YourTextBox" onkeypress="return isNumber(event)"></asp:TextBox>
    
    <!-- This script will trigger on any keypress and check for any numeric values -->
    <script type='text/javascript'>
        function isNumber(evt) {
            evt = (evt) ? evt : window.event;
            var charCode = (evt.which) ? evt.which : evt.keyCode;
            if (charCode > 31 && (charCode < 48 || charCode > 57)) {
                return false;
            }
            return true;
        }
    </script>

    Another option, would be to define a Regular Expression containing the characters that you want to allow and stripping out anything that doesn't match that restriction. You could use this along with the previously mentioned MaxLength property to limit a TextBox to just 10 alphanumeric characters as seen below : 

    <asp:TextBox ID="YourTextBox" runat="server" MaxLength='10' onkeyup="StripNonAlphanumeric(this)"></asp:TextBox>>
      
    <script type='text/javascript'>
          function StripNonAlphanumeric(source){
            // This regular expression will match and replace all non alphanumeric characters
            source.value = source.value.replace(/[^a-zA-Z0-9]/g, '');
          }
    </script>
    Wednesday, March 26, 2014 9:30 PM
  • User-1824994464 posted

    Hi,

    Thanks for your reply. Actually  this is a MVC Web Application.  I want the user to enter float or integer must be less than 10.  It is not the max length 10. I want the user to

    enter  like  1,2,3,4,5,6,7,8,9,10 or 1.1, 2.5,  9.7...etc  must be less than 10.

    This is my Html

    @Html.TextBoxFor(f => f.MarketInfo.Agency.Other_CashCommission, new { maxlength = "5",  onkeypress = "return NumberAndFloat(event,this.id)", @class="input" })

    below script is to enter  int or float.

     function NumberAndFloat(event, field) {
    
            if (navigator.appName == "Microsoft Internet Explorer") {
                var val = document.getElementById(field).value;
                var Key = window.event.keyCode;
                if ((Key >= 48 && Key <= 57) || (Key == 46 && val.indexOf(".") == -1)) {
                    return true;
                }
                else {
                    return false;
                }
            }
            else {
                var val = document.getElementById(field).value;
                var Key = event.which;
                if (Key == 8) {
                    return true;
                }
                else if (Key == 0) {
                    return true;
                }
                else if ((Key >= 48 && Key <= 57) || (Key == 46 && val.indexOf(".") == -1)) {
                    return true;
                }
                else {
                    return false;
                }
    
            }
        }

    Wednesday, March 26, 2014 11:23 PM
  • User281315223 posted

    I apologize for some of the additional responses as they aren't really related to your issue.

    Consider the first example using the autonumeric plug-in that I provided, which using MVC might look like :

    <!DOCTYPE html>
    <html>
    <head>
      <meta charset="utf-8">
      <title>JS Bin</title>
      <!-- jQuery and Plugin References -->
      <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
      <script src="http://www.decorplanit.com/plugin/autoNumeric-1.9.18.js"></script>
      <script type='text/javascript'>
        $(function($) {
          // Defines your numeric masking for any elements with the class numericOnly and sets the maximum to 10
          $('.numericOnly').autoNumeric('init', { vMax: 10.00 });    
        });  
      </script>
    </head>
    <body>
      <!-- Define your specific properties for your field -->
      @Html.TextBoxFor(f => f.MarketInfo.Agency.Other_CashCommission, new { @class = "input numericonly" })
    </body>
    </html>

    A plugin is likely a better choice simply because it will not only perform better in a cross-browser sense, but its likely going to be much more reliable and well tested than one that you elect to write yourself.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, March 27, 2014 12:53 PM