[javascript] Allow only numbers and dot in script

Am using this javascript for restrict users to type only numbers and only one dot as decimal separator.

<script type="text/javascript">
 function fun_AllowOnlyAmountAndDot(txt)
        {
            if(event.keyCode > 47 && event.keyCode < 58 || event.keyCode == 46)
            {
               var txtbx=document.getElementById(txt);
               var amount = document.getElementById(txt).value;
               var present=0;
               var count=0;

               if(amount.indexOf(".",present)||amount.indexOf(".",present+1));
               {
              // alert('0');
               }

              /*if(amount.length==2)
              {
                if(event.keyCode != 46)
                return false;
              }*/
               do
               {
               present=amount.indexOf(".",present);
               if(present!=-1)
                {
                 count++;
                 present++;
                 }
               }
               while(present!=-1);
               if(present==-1 && amount.length==0 && event.keyCode == 46)
               {
                    event.keyCode=0;
                    //alert("Wrong position of decimal point not  allowed !!");
                    return false;
               }

               if(count>=1 && event.keyCode == 46)
               {

                    event.keyCode=0;
                    //alert("Only one decimal point is allowed !!");
                    return false;
               }
               if(count==1)
               {
                var lastdigits=amount.substring(amount.indexOf(".")+1,amount.length);
                if(lastdigits.length>=2)
                            {
                              //alert("Two decimal places only allowed");
                              event.keyCode=0;
                              return false;
                              }
               }
                    return true;
            }
            else
            {
                    event.keyCode=0;
                    //alert("Only Numbers with dot allowed !!");
                    return false;
            }

        }

    </script>

<td align="right">
<asp:TextBox ID="txtQ1gTarget" runat="server" Width="30px" CssClass="txtbx" MaxLength="6" onkeypress="return fun_AllowOnlyAmountAndDot(this);"></asp:TextBox>
</td>

But the onkeypress(this) event returns object required error in that function at this place

var amount = document.getElementById(txt).value;

What's my mistake here?

This question is related to javascript asp.net regex validation

The answer is


<input type="text" class="decimal" value="" />
$('.decimal').keypress(function(evt){
    return (/^[0-9]*\.?[0-9]*$/).test($(this).val()+evt.key);
});

I think this simple solution may be.


You can use this

Javascript

function isNumber(evt) {
    evt = (evt) ? evt : window.event;
    var charCode = (evt.which) ? evt.which : evt.keyCode;
    if (charCode > 31 && (charCode < 48 || charCode > 57)&&(charCode!=46)) {
        return false;
    }
    return true;
}

Usage

 <input onkeypress="return isNumber(event)" class="form-control">

This works best for me.

I also apply a currency formatter on blur where the decimal part is rounded at 2 digits just in case after validating with parseFloat.

The functions that get and set the cursor position are from Vishal Monpara's blog. I also do some nice stuff on focus with those functions. You can easily remove 2 blocks of code where 2 decimals are forced if you want and get rid of the set/get caret functions.

<html>
<body>
<input type="text" size="30" maxlength="30" onkeypress="return numericValidation(this,event);" />
<script language="JavaScript">
    function numericValidation(obj,evt) {
        var e = event || evt; // for trans-browser compatibility

        var charCode = e.which || e.keyCode;        

        if (charCode == 46) { //one dot
            if (obj.value.indexOf(".") > -1)
                return false;
            else {
                //---if the dot is positioned in the middle give the user a surprise, remember: just 2 decimals allowed
                var idx = doGetCaretPosition(obj);
                var part1 = obj.value.substr(0,idx),
                    part2 = obj.value.substring(idx);

                if (part2.length > 2) {
                    obj.value = part1 + "." + part2.substr(0,2);
                    setCaretPosition(obj, idx + 1);
                    return false;
                }//---

                //allow one dot if not cheating
                return true;
            }
        }
        else if (charCode > 31 && (charCode < 48 || charCode > 57)) { //just numbers
            return false;
        }

        //---just 2 decimals stubborn!
        var arr = obj.value.split(".") , pos = doGetCaretPosition(obj);

        if (arr.length == 2 && pos > arr[0].length && arr[1].length == 2)                               
            return false;
        //---

        //ok it's a number
        return true;
    }

    function doGetCaretPosition (ctrl) {
        var CaretPos = 0;   // IE Support
        if (document.selection) {
        ctrl.focus ();
            var Sel = document.selection.createRange ();
            Sel.moveStart ('character', -ctrl.value.length);
            CaretPos = Sel.text.length;
        }
        // Firefox support
        else if (ctrl.selectionStart || ctrl.selectionStart == '0')
            CaretPos = ctrl.selectionStart;
        return (CaretPos);
    }

    function setCaretPosition(ctrl, pos){
        if(ctrl.setSelectionRange)
        {
            ctrl.focus();
            ctrl.setSelectionRange(pos,pos);
        }
        else if (ctrl.createTextRange) {
            var range = ctrl.createTextRange();
            range.collapse(true);
            range.moveEnd('character', pos);
            range.moveStart('character', pos);
            range.select();
        }
    }
</script>
</body>
</html>

 <input type="text" class="form-control" id="odometer_reading" name="odometer_reading"  placeholder="Odometer Reading" onblur="odometer_reading1();" onkeypress='validate(event)' required="" />
<script>
                function validate(evt) {
                  var theEvent = evt || window.event;
                  var key = theEvent.keyCode || theEvent.which;
                  key = String.fromCharCode( key );
                  var regex = /[0-9]|\./;
                  if( !regex.test(key) ) {
                    theEvent.returnValue = false;
                    if(theEvent.preventDefault) theEvent.preventDefault();
                  }
                }
            </script>

Hope this could help someone

$(document).on("input", ".numeric", function() {
this.value = this.value.match(/^\d+\.?\d{0,2}/);});

<script type="text/javascript">
    function numericValidation(txtvalue) {
        var e = event || evt; // for trans-browser compatibility
        var charCode = e.which || e.keyCode;
        if (!(document.getElementById(txtvalue.id).value))
         {
            if (charCode > 31 && (charCode < 48 || charCode > 57))
                return false;
            return true;
        }
        else {
               var val = document.getElementById(txtvalue.id).value;
            if(charCode==46 || (charCode > 31 && (charCode > 47 && charCode < 58)) )
             {
                var points = 0;            
                points = val.indexOf(".", points);                    
                if (points >= 1 && charCode == 46)
                {      
                   return false;
                }                 
                if (points == 1) 
                {
                    var lastdigits = val.substring(val.indexOf(".") + 1, val.length);
                    if (lastdigits.length >= 2)
                    {
                        alert("Two decimal places only allowed");
                        return false;
                    }
                }
                return true;
            }
            else {
                alert("Only Numarics allowed");
                return false;
            }
        }
    }

</script>
<form id="form1" runat="server">
<div>
  <asp:TextBox ID="txtHDLLevel" MaxLength="6" runat="server" Width="33px" onkeypress="return numericValidation(this);"  />
</div>
</form>


 <script type="text/Javascript">
        function checkDecimal(inputVal) {
            var ex = /^[0-9]+\.?[0-9]*$/;
            if (ex.test(inputVal.value) == false) {
                inputVal.value = inputVal.value.substring(0, inputVal.value.length - 1);
            }
        }
</script>

try This Code

_x000D_
_x000D_
var check = function(evt){_x000D_
_x000D_
var data = document.getElementById('num').value;_x000D_
if((evt.charCode>= 48 && evt.charCode <= 57) || evt.charCode== 46 ||evt.charCode == 0){_x000D_
if(data.indexOf('.') > -1){_x000D_
 if(evt.charCode== 46)_x000D_
  evt.preventDefault();_x000D_
}_x000D_
}else_x000D_
evt.preventDefault();_x000D_
};_x000D_
_x000D_
document.getElementById('num').addEventListener('keypress',check);
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<title>Page Title</title>_x000D_
</head>_x000D_
<body>_x000D_
<input type="text" id="num" value="" />_x000D_
_x000D_
_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_


Use Jquery instead. Add a decimal class to your textbox:

<input type="text" class="decimal" value="" />

Use this code in your JS. It checks for multiple decimals and also restrict users to type only numbers.

$('.decimal').keyup(function(){
    var val = $(this).val();
    if(isNaN(val)){
         val = val.replace(/[^0-9\.]/g,'');
         if(val.split('.').length>2) 
             val =val.replace(/\.+$/,"");
    }
    $(this).val(val); 
});?

Check this fiddle: http://jsfiddle.net/2YW8g/

Hope it helps.


Try this for multiple text fileds (using class selector):

Click here for example..

_x000D_
_x000D_
var checking = function(event){_x000D_
 var data = this.value;_x000D_
 if((event.charCode>= 48 && event.charCode <= 57) || event.charCode== 46 ||event.charCode == 0){_x000D_
  if(data.indexOf('.') > -1){_x000D_
    if(event.charCode== 46)_x000D_
      event.preventDefault();_x000D_
  }_x000D_
 }else_x000D_
  event.preventDefault();_x000D_
 };_x000D_
_x000D_
 function addListener(list){_x000D_
  for(var i=0;i<list.length;i++){_x000D_
      list[i].addEventListener('keypress',checking);_x000D_
     }_x000D_
 }_x000D_
 var classList = document.getElementsByClassName('number');_x000D_
 addListener(classList);
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<title>Page Title</title>_x000D_
</head>_x000D_
<body>_x000D_
  <input type="text" class="number" value="" /><br><br>_x000D_
  <input type="text" class="number" value="" /><br><br>_x000D_
  <input type="text" class="number" value="" /><br><br>_x000D_
  <input type="text" class="number" value="" /><br><br>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_


_x000D_
_x000D_
function isNumberKey(evt,id)_x000D_
{_x000D_
 try{_x000D_
        var charCode = (evt.which) ? evt.which : event.keyCode;_x000D_
  _x000D_
        if(charCode==46){_x000D_
            var txt=document.getElementById(id).value;_x000D_
            if(!(txt.indexOf(".") > -1)){_x000D_
 _x000D_
                return true;_x000D_
            }_x000D_
        }_x000D_
        if (charCode > 31 && (charCode < 48 || charCode > 57) )_x000D_
            return false;_x000D_
_x000D_
        return true;_x000D_
 }catch(w){_x000D_
  alert(w);_x000D_
 }_x000D_
}
_x000D_
<html>_x000D_
  <head>_x000D_
  </head>_x000D_
  <body>_x000D_
    <INPUT id="txtChar" onkeypress="return isNumberKey(event,this.id)" type="text" name="txtChar">_x000D_
  </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_


function isNumber(evt) {
    evt = (evt) ? evt : window.event;
    var charCode = (evt.which) ? evt.which : evt.keyCode;
    if (charCode > 31 && (charCode < 46 || charCode > 57)) {
        return false;
    }
    return true;
}

you should use this function and write the properties of this element ;

HTML Code:

<input id="deneme" data-mini="true" onKeyPress="return isNumber(event)" type="text"/>`

Just add the code below in your input text:

onkeypress='return event.charCode == 46 || (event.charCode >= 48 && event.charCode <= 57)'

This function will prevent entry of anything other than numbers and a single dot.

_x000D_
_x000D_
function validateQty(el, evt) {_x000D_
   var charCode = (evt.which) ? evt.which : event.keyCode_x000D_
    if (charCode != 45 && charCode != 8 && (charCode != 46) && (charCode < 48 || charCode > 57))_x000D_
        return false;_x000D_
    if (charCode == 46) {_x000D_
        if ((el.value) && (el.value.indexOf('.') >= 0))_x000D_
            return false;_x000D_
        else_x000D_
            return true;_x000D_
    }_x000D_
    return true;_x000D_
    var charCode = (evt.which) ? evt.which : event.keyCode;_x000D_
    var number = evt.value.split('.');_x000D_
    if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57)) {_x000D_
        return false;_x000D_
    }_x000D_
};
_x000D_
<input type="text" onkeypress='return validateQty(this,event);'>
_x000D_
_x000D_
_x000D_


This is a great place to use regular expressions.

By using a regular expression, you can replace all that code with just one line.

You can use the following regex to validate your requirements:

[0-9]*\.?[0-9]*

In other words: zero or more numeric characters, followed by zero or one period(s), followed by zero or more numeric characters.

You can replace your code with this:

function validate(s) {
    var rgx = /^[0-9]*\.?[0-9]*$/;
    return s.match(rgx);
}

That code can replace your entire function!

Note that you have to escape the period with a backslash (otherwise it stands for 'any character').

For more reading on using regular expressions with javascript, check this out:

You can also test the above regex here:


Explanation of the regex used above:

  • The brackets mean "any character inside these brackets." You can use a hyphen (like above) to indicate a range of chars.

  • The * means "zero or more of the previous expression."

  • [0-9]* means "zero or more numbers"

  • The backslash is used as an escape character for the period, because period usually stands for "any character."

  • The ? means "zero or one of the previous character."

  • The ^ represents the beginning of a string.

  • The $ represents the end of a string.

  • Starting the regex with ^ and ending it with $ ensures that the entire string adheres to the regex pattern.

Hope this helps!


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to asp.net

RegisterStartupScript from code behind not working when Update Panel is used You must add a reference to assembly 'netstandard, Version=2.0.0.0 No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization How to use log4net in Asp.net core 2.0 Visual Studio 2017 error: Unable to start program, An operation is not legal in the current state How to create roles in ASP.NET Core and assign them to users? How to handle Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause() ASP.NET Core Web API Authentication Could not load file or assembly 'CrystalDecisions.ReportAppServer.CommLayer, Version=13.0.2000.0 WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery

Examples related to regex

Why my regexp for hyphenated words doesn't work? grep's at sign caught as whitespace Preg_match backtrack error regex match any single character (one character only) re.sub erroring with "Expected string or bytes-like object" Only numbers. Input number in React Visual Studio Code Search and Replace with Regular Expressions Strip / trim all strings of a dataframe return string with first match Regex How to capture multiple repeated groups?

Examples related to validation

Rails 2.3.4 Persisting Model on Validation Failure Input type number "only numeric value" validation How can I manually set an Angular form field as invalid? Laravel Password & Password_Confirmation Validation Reactjs - Form input validation Get all validation errors from Angular 2 FormGroup Min / Max Validator in Angular 2 Final How to validate white spaces/empty spaces? [Angular 2] How to Validate on Max File Size in Laravel? WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery