Input validations - Allow only numeric and decimal

Input validation

by Sushil Mahajan

HTML

<input id="numericValue"/>
Allow only numeric or decimal values

JavaScript

$('document').ready(function () {
	$("#numericValue").keypress(function (e){
  		allowOnlyNumeric(e, false, true, 3);
  });
});


/**
 * This function will restrict user to enter only numeric or decimal value in the input box.
 * Should be called on keypress event
 * @param event
 * @param boolean allowNegative, default false
 * @param boolean allowDecimal, default true
 * @param Integer digitsAfterDecimal
 */
allowOnlyNumeric = function(event, allowNegative, allowDecimal, digitsAfterDecimal) {
    var isDotAllowed = true;

    if (allowDecimal != undefined && allowDecimal == false) {
    	isDotAllowed = false;
    }
       
    if ($(event.currentTarget).val().indexOf(".") > -1){
        isDotAllowed = false;
    }

    if (digitsAfterDecimal != undefined && !isNaN(digitsAfterDecimal)) {
    	var value = $(event.currentTarget).val();
    	var indexOfDot = value.indexOf(".");
    	if (indexOfDot > -1) {
    		var valueArray = value.split(".");
    		if (valueArray[1].length >= Number(digitsAfterDecimal)){
        	var cursorIndex = $(event.currentTarget).getCursorPosition();
          if(cursorIndex > valueArray[0].length) {
          	// when more than configured decimal digits
						event.preventDefault();
            return;
          }
    		}
    	}
    }

    var allowedKeys = ['Backspace','Down','Left','Right','Up','Del'];
    if((allowedKeys.indexOf(event.key) == -1) && isNaN(String.fromCharCode(event.which))){
        if (String.fromCharCode(event.which) != ".") {  
        	if (allowNegative == true) {
            	if (String.fromCharCode(event.which) == "-" &&    	  $(event.currentTarget).val().indexOf("-") == -1
            			&& $(event.currentTarget).getCursorPosition() == 0){
                    return;
                }
        	}
        	event.preventDefault();
        } else {
            if (isDotAllowed == false) {
                event.preventDefault();
            } else {
                isDotAllowed = false;
            }
        }
   ...