If you want to restrict input (as opposed to validation), you could work with the key events. something like this:

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

And:

jQuery('.numbersOnly').keyup(function () { 
    this.value = this.value.replace(/[^0-9\.]/g,'');
});

or, we can update this after the user has 'left' the field, with the on change event, this way the user can still navigate through the text with the arrow keys.

jQuery('.numbersOnly').on('change', function () { 
    this.value = this.value.replace(/[^0-9\.]/g,'');
});

This immediately lets the user know that they can't enter alpha characters, etc. rather than later during the validation phase.

You'll still want to validate because the input might be filled in by cutting and pasting with the mouse or possibly by a form autocompleter that may not trigger the key events.

Fiddle: http://jsfiddle.net/shannonhochkins/eu7P9/

Answer from Shannon Hochkins on Stack Overflow
🌐
Code2night
code2night.com › Blog › MyBlog › Decimal-validation-in-JavaScript
Decimal validation in JavaScript | Code2night.com
August 14, 2022 - <form> <div class="form-group row"> <label for="inputPassword" class="col-sm-2 col-form-label">Enter Only Number And Decimal</label> <div class="col-sm-10"> <input type="text" class="form-control" id="inputNumberWithDecimal" placeholder="Enter Only Number And Decimal" value="" name="inputNumberWithDecimal" onkeypress="return onlyNumberWithDecimal(event)" /> </div> </div> </form> Here is how to validate the input only to accept Number And Decimal this will only take Number And Decimal values like "12.5"
🌐
Blogger
webleader-php.blogspot.com › 2011 › 12 › onkeypress-javascript-numeric-and.html
PHP and JavaScript: Onkeypress Javascript Numeric and Decimal Validation
function digits(obj, e, allowDecimal, allowNegative) { var key; var isCtrl = false; var keychar; var reg; if(window.event) { key = e.keyCode; isCtrl = window.event.ctrlKey } else if(e.which) { key = e.which; isCtrl = e.ctrlKey; } if (isNaN(key)) return true; keychar = String.fromCharCode(key); // check for backspace or delete, or if Ctrl was pressed if (key == 8 || isCtrl) { return true; } reg = /\d/; var isFirstN = allowNegative ? keychar == '-' && obj.value.indexOf('-') == -1 : false; var isFirstD = allowDecimal ?
🌐
Experts Exchange
experts-exchange.com › questions › 23976512 › Validate-the-textbox-with-decimal-values-only-using-javascript.html
Solved: Validate the textbox with decimal values only using javascript. | Experts Exchange
December 11, 2008 - 2)after decimal point,it should accept the values upto two digits only.it should not take more than two digits. 3)here you should raise onkeypress or onkeydown javascript events to perform the validation.
🌐
EncodedNA
encodedna.com › 2013 › 05 › enter-only-numbers-using-jquery.htm
Enter Only Numbers and Decimal Values Using jQuery
$("#tb1, #tb2").keypress(function(event){ return isNumber(event, this); }); }); // THE SCRIPT THAT CHECKS IF THE KEY PRESSED IS A NUMERIC OR DECIMAL VALUE. function isNumber(evt, element) { var charCode = (evt.which) ? evt.which : event.keyCode if ( (charCode != 45 || $(element).val().indexOf('-') ...
🌐
Wikitechy
wikitechy.com › tutorials › javascript › validate-decimal-numbers
[Solved-100% Working Code] - Validate decimal numbers - javascript tutorial | wikitechy
decimal number validation in javascript on keypressdecimal validation in javascript using regular expressionjavascript isdecimalnumeric validation in javascript for textboxjavascript validate number onlyjavascript check how many decimal placesjavascript isnumeric stringjquery isnumericallow only decimal numbers in textbox javascriptallow only two digits after decimal using javascriptjquery 2 decimal places validationjavascript allow only 2 decimal placesallow only two digits after decimal using jqueryjquery decimal validation on keypressjavascript 2 decimal places validationallow only numbers
Find elsewhere
🌐
ASPSnippets
aspsnippets.com › Articles › 948 › Numeric-KeyPress-Validation-Allow-only-numbers-validation-on-KeyPress-in-TextBox-using-JavaScript
Numeric KeyPress Validation Allow only numbers validation on KeyPress in TextBox using JavaScript
January 29, 2019 - In this article I will explain ... in TextBox. ... Numeric Value: <input type="text" id="text1" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;" />...
🌐
CodeProject
codeproject.com › Questions › 189890 › Decimal-Validation-OnKeypress-all-browser-Javscrip
[Solved] Decimal Validation OnKeypress all browser Javscript - CodeProject
May 2, 2011 - Artificial Intelligence · ASP.NET · JavaScript · Internet of Things · C / C++ / MFC> ATL / WTL / STL · Managed C++/CLI · C# Free Tools · Objective-C and Swift · Database · Hardware & Devices> System Admin · Hosting and Servers · Java · Linux Programming ·
Top answer
1 of 7
39

You were almost there. Just check that there are no more than 2 characters after the decimal.

UPDATE 1 - check carat position to allow character insertion before the decimal.
UPDATE 2 - correct issue pointed out by ddlab's comment and only allow one dot.

 function validateFloatKeyPress(el, evt) {
    var charCode = (evt.which) ? evt.which : event.keyCode;
    var number = el.value.split('.');
    if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57)) {
        return false;
    }
    //just one dot (thanks ddlab)
    if(number.length>1 && charCode == 46){
         return false;
    }
    //get the carat position
    var caratPos = getSelectionStart(el);
    var dotPos = el.value.indexOf(".");
    if( caratPos > dotPos && dotPos>-1 && (number[1].length > 1)){
        return false;
    }
    return true;
}

//thanks: http://javascript.nwbox.com/cursor_position/
function getSelectionStart(o) {
    if (o.createTextRange) {
        var r = document.selection.createRange().duplicate()
        r.moveEnd('character', o.value.length)
        if (r.text == '') return o.value.length
        return o.value.lastIndexOf(r.text)
    } else return o.selectionStart
}

http://jsfiddle.net/S9G8C/1/
http://jsfiddle.net/S9G8C/203/

2 of 7
12

Consider leveraging HTML5's Constraint Validation API. It doesn't necessarily prevent typing invalid values, but the field is marked invalid and it halts submission of the <form> (by default). I added the <output> to illustrate why the browser considers e.g. "1.100" a valid value (it sees the numeric value as "1.1").

<input id="n" type="number" step=".01">

var
  n = document.getElementById('n'),
  o = document.getElementById('o'),
  didInputN = function(e) {
    o.value = n.valueAsNumber;
  };

n.addEventListener('input', didInputN);
input:invalid {
  color: white;
  background-color: red;
}
<input id="n" type="number" step=".01">
<output id="o" for="n"></output>

Philosophically, you might consider this a more usable approach as it allows the user to paste an invalid entry and edit it directly in the field.

🌐
EncodedNA
encodedna.com › 2012 › 12 › JavaScript-accept-only-numbers-textbox.htm
Accept only numbers with decimal in a textbox using JavaScript
It is always advisable to validate data on the client side before submission and again on the server side before processing or saving it. Similar example: 👉 How to force users to enter only numbers in a textbox using jQuery (A cross browser solution) ... &ltbody> &ltdiv> Enter only numbers with a Decimal value: &ltinput type='text' id='tbNumbers' value='' onkeypress='javascript: return isNumber(event)' autocomplete='off' /> &lt/div> &lt/body> &ltscript> // Write the validation script.
Top answer
1 of 2
1

Maybe you can just correct the value using parseFloat:

<input onchange="this.value = parseFloat(this.value) || ''" type="text" />

I changed it to onchange because otherwise it would prevent you from typing a . at all. This however means it will only validate once when you blur the input.

EDIT


Like this then?

JS:

function validateFloatKeyPress(el, evt) {

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

    if (charCode == 46 && el.value.indexOf(".") !== -1) {
        return false;
    }

    return true;
}

HTML:

<input onkeypress="return validateFloatKeyPress(this, event)" type="text" />
2 of 2
0

I also having same problem.This code has solved my problem.It's not only foramt yous decimal number but also will eliminate blank spaces. Try this.As in my condition i was allowing user to enter '+' or '-' so i check for this validation also.I have called this function onblur event.Hope this help u,

<script type="text/javascript">
        function checkforvalidation() {
            var txtvalue = document.getElementById('<%=txtspherical.ClientID %>').value;
            var leftstr = "";
            var rightstr = "";
            var tempstr = "";
            var operator = "";
            txtvalue = txtvalue.replace(/\s/g, '');
            document.getElementById('<%=txtspherical.ClientID %>').value = txtvalue;
            if (txtvalue.indexOf(".") != -1) {

                leftstr = txtvalue.split(".")[0];
                rightstr = txtvalue.split(".")[1];
                if (leftstr.indexOf("-") == 0 || leftstr.indexOf("+") == 0) {

                    operator = leftstr.substr(0, 1);
                    tempstr = leftstr.substr(1, leftstr.length - 1);

                    leftstr = ltrim(tempstr, '0');

                    if (leftstr.length == 0) {
                        leftstr = '0';
                    }

                    if (rightstr.indexOf("-") == -1 || rightstr.indexOf("+") == -1) {

                        rightstr = ltrim(rightstr, '0');

                        rightstr = chkdecimalpoints(rightstr);
                        if (operator != null || operator != "") {
                            txtvalue = operator + leftstr + "." + rightstr;
                        }
                        else {
                            txtvalue = leftstr + "." + rightstr;
                        }
                        document.getElementById('<%=txtspherical.ClientID %>').value = txtvalue;
                    }
                    else {
                        document.getElementById('<%=txtspherical.ClientID %>').value = "";
                    }
                }
                else {

                    tempstr = leftstr.substr(0, leftstr.length);
                    leftstr = ltrim(tempstr, '0');
                    if (leftstr.length == 0) {
                        leftstr = '0';
                    }
                    if (rightstr.indexOf("-") == -1 || rightstr.indexOf("+") == -1) {

                        rightstr = rtrim(rightstr, '0');
                        rightstr = chkdecimalpoints(rightstr);
                        txtvalue = leftstr + "." + rightstr;
                        document.getElementById('<%=txtspherical.ClientID %>').value = txtvalue;
                    }
                }
            }
            else if (txtvalue.indexOf("-") == -1 || txtvalue.indexOf("+") == -1) {

                txtvalue = ltrim(txtvalue, '0');
                if (txtvalue.length == 0) {
                    txtvalue = '0';
                }
                if (operator != null || operator != "") {
                    txtvalue = operator + txtvalue + ".00";
                }
                // txtvalue = leftstr + "." + rightstr;
                document.getElementById('<%=txtspherical.ClientID %>').value = txtvalue;
            }
            else if (txtvalue.indexOf("-") == 0 || txtvalue.indexOf("+") == 0) {

                operator = txtvalue.substr(0, 1);
                tempstr = txtvalue.substr(1, leftstr.length - 1);
                txtvalue = alltrim(tempstr, '0');
                if (operator != null || operator != "") {
                    txtvalue = operator + txtvalue + ".00";
                    document.getElementById('<%=txtspherical.ClientID %>').value = txtvalue;
                }
            }
        }

        function chkdecimalpoints(rightstr) {
            if (rightstr.length == 0) {
                rightstr = '00';

                return rightstr;

            }
            else if (rightstr.length == 1) {
                rightstr = rightstr + '0';
                return rightstr;
            }
            else if (rightstr.length > 2) {

                var tempvar = rightstr.substr(2, 1);

                if (tempvar >= 5) {

                    tempvar = parseInt(rightstr.substr(1, 1)) + 1;
                    tempvar = rightstr.substr(0, 1) + tempvar.toString();
                    if (tempvar.length > 2) {
                        tempvar = tempvar.substr(0, 2);
                    }
                    return tempvar;
                }
                else {

                    tempvar = rightstr.substr(0, 2);
                    return tempvar;
                }
            }
            else {
                return rightstr;
            }
        }
        function ltrim(str, chars) {
            chars = chars || "\\s";
            return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
        }
        function rtrim(str, chars) {
            chars = chars || "\\s";
            return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
        }
        function alltrim(str, chars) {
            chars = chars || "\\s";
            return str.replace(new RegExp("^[" + chars + "]+$", "g"), "");
        }

    </script>

HTML Source:

<asp:TextBox ID="txtspherical" runat="server" OnBlur="javascript:checkforvalidation();">
        </asp:TextBox>
🌐
C# Corner
c-sharpcorner.com › blogs › numeric-keypress-validation-in-textbox-using-javascript1
Numeric KeyPress Validation in TextBox using JavaScript
May 19, 2020 - Paste the following JavaScript function in the head section of the Home.aspx page. ... <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Home.aspx.cs" Inherits="NumericKeyPressValidation.Home" %> ... Numeric Value: <input type="text" id="text1" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;" />