Anil Talla
Anil Talla

Reputation: 709

Number validation along with decimals in key press event

I am doing validation of number except on case. I am doing validation in key press event.

This is the process how am doing my validation..

Output length = Integral + decimals

Example: Integral = 5, decimals = 3

If user enter five digits then am not allowing to enter 6th digit. (i.e. 12345). But if he type '.' then after am allowing to 3 decimals (i.e. 12345.678). This is working perfectly.

Am facing the issue with below case.

If user enter 1.234 then he navigating to before '.' place using arrows or by mouse click, then user unable to enter another digit. Because I am checking either the integral part or decimal part match the length then I am returning false.

Can any one help me out this. I can do with key up event, but I am trying to achieve this by key press event only. Is there any way to get the position where user entering the digit, if yes then I can get one solution.

var integral = 5, decimals = 3; 
//below code in the key press event
if ([8, 9, 13, 37, 39,46].indexOf(e.keyCode) != -1) {
    return true;
} else if (e.keyCode == 190 && !e.shiftKey && decimals) {
    _value = $(this).val();
    if (_value.indexOf('.') != -1) {
        return false;
    }
    return true;
} else if (48 >= e.keyCode || e.keyCode <= 57) {
    _value = $(this).val();
    if (decimals) {
        _value = _value.split('.');
        if (_value[0].length == integral || (_value[1] || '').length == decimals) {
            return false;
        }
        return true;
    } else {
        if (_value.length == integral) {
            return false;
        }
        return true;
    }
}
return false;

Upvotes: 3

Views: 1764

Answers (2)

longestwayround
longestwayround

Reputation: 1019

If you already know how to do it with the keyup event, then you should be able to take that code and insert it into the keypress handler and implement it on the value that would be in the input if you pass the value through. For example (I assume your validation works like in the example):

$("#myinput").keypress(function (e) {  
    //first figure out what the value would be if the keypress were passed through
    var key=(e.which) ? e.which : e.keyCode;  
    var inputvalue=String.fromCharCode((96 <= key && key <= 105)? key-48 : key)
    var caretPos = document.getElementById("myinput").selectionStart;
    var currentvalue=$("#myinput").val();
    var outputstring=currentvalue.substring(0, caretPos) + inputvalue + currentvalue.substring(caretPos);

    //allow decimals through
    if (outputstring===".") {    
          e.preventDefault();           
          $("#myinput").val("0.");
          return false;
    }
    //cancel keypress if they string already has a decimal
    if(key===46) return (outputstring.split(".").length - 1)>2;          

    //now perform the truncation and validation
    e.preventDefault();   
    var outputvalue=parseFloat(outputstring);
    var decpart=Math.trunc((outputvalue- parseInt(outputvalue)) * 1000)/1000;
    var intpart=Math.floor(outputvalue);
    //perform your test on the output value here - only need to test the integer part, since the decimal part is truncated
    var outputtest=String(intpart).length<=5; 
    if (outputtest){         
          //insert the value if it looks okay      
          $("#myinput").val(intpart+decpart);              
    }
    return false;
});

Upvotes: 0

Anil Talla
Anil Talla

Reputation: 709

I used selectionEnd for getting position of where user is typing the digit. Using that I did it.

var evt = e.target || e.srcElement;
        _value = $(evt).val();
        if ([8, 9, 13, 37, 39, 46].indexOf(e.keyCode) != -1) {
            return true;
        }
        else if (e.keyCode == 190 && !e.shiftKey && decimals) {
            if (_value.indexOf('.') != -1) {
                return false;
            }
            return true;
        }
        else if (48 >= e.keyCode || e.keyCode <= 57) {
            if (decimals) {
                var isHavingDot = false;
                var dotPosition = '';
                if (_value.indexOf('.') != -1) {
                    isHavingDot = true;
                    dotPosition = _value.indexOf('.')
                }
                var length = _value.length;
                if (isHavingDot) {
                    _value = _value.split('.');
                    if (evt.selectionEnd <= dotPosition) {
                        if (_value[0].length >= integral) {
                            return false;
                        }
                    }
                    else if ((_value[1] || '').length >= decimals) {
                        return false;
                    }
                }
                else {
                    if (_value.length >= integral) {
                        return false;
                    }
                }
                return true;
            }
            else {
                if (_value.length == integral) {
                    return false;
                }
                return true;
            }
        }
        return false;

Upvotes: 1

Related Questions