Allow only float numbers with 2 decimals and 1 decimal dot


// credit to http://stackoverflow.com/questions/21374605/java-script-to-allow-only-numbers-comma-dot-back-space

function _validateFloatNumber(element, evt) {

	var event, key, numberSplitByDot,

		caretPos, dotPos, regex, notValid = false;



	event = evt || window.event;

	key = event.keyCode || event.which;

	key = String.fromCharCode(key);

	if (key.length == 0) { // do nothing if it is non-char button

		return;

	}

	if (event.charCode == 0) { // in Firefox key will be not empty but charCode will be 0 for non-char buttons

		return;

	}



	regex = /^[0-9.\b]+$/; // allow only numbers and decimal dot

	if (!regex.test(key)) {

		notValid = true;

	}



	numberSplitByDot = element.value.split('.');

	if (numberSplitByDot.length > 1 && key == '.') { // only 1 dot

		notValid = true;

	}



	caretPos = _getCursorPosition(element);

	dotPos = element.value.indexOf('.');

	if (caretPos > dotPos && numberSplitByDot[1] && numberSplitByDot[1].length > 1) { // only 2 digits after dot

		notValid = true;

	}



	if (notValid) {

		event.returnValue = false;

		if (event.preventDefault) {

			event.preventDefault();

		}

	}

}



// credit to http://stackoverflow.com/questions/2897155/get-cursor-position-in-characters-within-a-text-input-field

function _getCursorPosition(element) {

	var caretPos = 0;

	if ('selectionStart' in element) { // modern browsers

		caretPos = element.selectionStart;

	} else if (document.selection) { // IE

		element.focus();

		var sel = document.selection.createRange(); // to get cursor position, get empty selection range

		var selLen = document.selection.createRange().text.length;

		sel.moveStart('character', -element.value.length); // move selection start to 0 position

		caretPos = sel.text.length - selLen; // the caret position is selection length

	}

	return caretPos;

}



jQuery(function($){ // document.ready and noConflict mode

        $('.target').on('keypress', function (event) {

              return _validateFloatNumber(this, event);

        });

});

Leave a Comment