0

How to allow only one "." in javascript during Keypress?

I have a code here:

function allowOneDot(txt) {

        if ((txt.value.split(".").length) > 1) {

          //here, It will return false; if the user type another "."

         } 
}
4
  • 1
    And what if the user pastes in a bunch of periods? What if they edit the javascript in their console to completely ignore this check? Make sure you are handling validation correctly and not making too many simplifications.
    – jbabey
    Jan 29, 2013 at 1:51
  • 1
    Why is it wrapped in a try/catch?
    – alex
    Jan 29, 2013 at 1:51
  • Why the try-catch? what are you asking about? Jan 29, 2013 at 1:52
  • txt.value.split(".").length) > 2 and input/keyup/keydown event
    – zb'
    Jan 29, 2013 at 1:53

4 Answers 4

6

I will reiterate what I said in my comment before the answer:

And what if the user pastes in a bunch of periods? What if they edit the javascript in their console to completely ignore this check? Make sure you are handling validation correctly and not making too many simplifications.

Now that we're proceeding at our own risk, here's how you would not allow a user typing more than one . (period) in a textbox:

document.getElementById('yourTextboxIDHere').onkeypress = function (e) {
    // 46 is the keypress keyCode for period     
    // http://www.asquare.net/javascript/tests/KeyCode.html
    if (e.keyCode === 46 && this.value.split('.').length === 2) {
        return false;
    }
}

Working demo

4
  • i still can paste any number of dots
    – zb'
    Jan 29, 2013 at 2:39
  • He said during key press not during paste. As jbabey has said javascript validation should never take the place of server side validation and should only be an addition to reduce the number of unnecessary submits to the server.
    – Neaox
    Jan 29, 2013 at 2:43
  • Thanks for the answer. I'd check this.value.indexOf('.') == this.value.lastIndexOf('.') instead of splitting though. Splitting will create new array on each key stroke, which shouldn't be desirable.
    – Gio
    Oct 12, 2017 at 20:10
  • Also keyCode for dot is 190, not 46. Plus, you should return false if the length doesn't equal 2, instead of the other way around. Also e.preventDefault() wouldn't hurt :)
    – Gio
    Oct 12, 2017 at 20:17
1

If you really want to allow one dot, even in the event of a user pasting text inside it, you should use keyup, not keypress, and you could keep your last text value in case you need to restore it. The drawback though, is that the input value will have already been changed, and you will see it getting corrected as you type.

(function() {
    var txt = document.getElementById('txt');
    var prevValue = txt.value;

    function allowOneDot(e) {
        var dots = 0;
        var length = txt.value.length;
        var text = txt.value;
        for(var i=0; i<length; i++) {
            if(text[i]=='.') dots++;
            if(dots>1) {
                txt.value = prevValue;
                return false;
            }
        }
        prevValue = text;
        return true;
    }
    txt.onkeyup = allowOneDot;
})();
0

I solved this question for the multipurpose use of decimal, number & alphanumeric field types.

For field types 'number' and 'alphanum', parameter l (lower L) is the string length allowed. For type 'decimal', it specifies the allowed number of decimal places.

function allowType(e, o = 'number', l = false) {
    let val = e.target.value;
    switch (o) {
        case 'alphanum':
            if (l) {
                val = val.substr(0, l).replaceAll(/[^0-9a-zA-Z]/gmi, '');
            } else {
                val = val.replaceAll(/[^0-9a-zA-Z]/gmi, '');
            }
            break;
        case 'number':
            if (l) {
                val = val.substr(0, l).replaceAll(/[^0-9]/gmi, '');
            } else {
                val = val.replaceAll(/[^0-9]/gmi, '');
            }
            break;
        case 'decimal':
            let i = val.search(/\./gmi);
            if (val.length === 1) {
                val = val.replaceAll(/[^0-9]/gmi, '');
            }
            if (i >= 0) {
                if (l) {
                    val = val.substr(0, i + 1) + val.substr(i).substr(0, l + 1).replaceAll(/\./gmi, '');
                } else {
                    val = val.substr(0, i + 1) + val.substr(i).replaceAll(/\./gmi, '');
                }
            }
            val = val.replaceAll(/[^0-9.]/gmi, '');
            break;
    }
    e.target.value = val;
}
<input type="text" oninput="allowType(event, 'decimal', 2)" placeholder="decimal">
<input type="text" oninput="allowType(event, 'number', 10)" placeholder="number">
<input type="text" oninput="allowType(event, 'alphanum', 5)" placeholder="alphanumeric">

-1
<input type="text" id="test" onkeyup="floatOnly(this);"/>



<script>
function floatOnly(i){
{
  if ((i.value).length > 0){else{i.value = i.value.replace(".." , ".");i.value = i.value.replace("..." , ".");i.value = i.value.replace(/[^0-9\.]/g , "");}}else{i.value = i.value="0";}}<script>
2
  • javascript solutions Sep 30, 2020 at 9:31
  • The code in this answer contains syntax errors. Has bad ideas such as mixing 2 string replaces with regex replace and only works for some use cases Sep 30, 2020 at 9:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.