Javascript validate number

Javascript validate number

this example allow only number character in you text field. This javascript validate number code can be tested at here .

—- JavaScript validate number code

function numeralsOnly(thisComp, e, isDecimal) {
	var key;
	var keychar;
	if (window.event) {
		key = window.event.keyCode;
	} else if (e) {
		key = e.which;
	} else {
		return true;
	}

	// check double period/decimal/point
	if (((thisComp.value).indexOf('.') > -1) && key == 46) {
		alert("Double period is not allow for this field.");
		return false;
	}

	var str = '0123456789';
	str += isDecimal ? '.' : '';
	keychar = String.fromCharCode(key);
	if ((key == null) || (key == 0) || (key == 8) || (key == 9) || (key == 13)
			|| (key == 27)) {
		return true;
	} else if (((str).indexOf(keychar) > -1)) {
		return true;
	}

	alert("Enter numerals only in this field.");
	thisComp.focus();
	// thisComp.select();
	return false;
}

——- html code

<input type="text" id="txtSkuPrice"  onkeypress="return numeralsOnly(this,event,true);"/>

numeralsOnly(this,event,true) -> for Double number use true and for integer number use false.

 

One thought on “Javascript validate number

  1. Hi,

    When using WordPress, try to install “SyntaxHighlighter Evolved” plugin. It makes the code reading definitely more friendly.

    “Allow number only in TextField by javascript” can also be achieve quickly and with two/three lines of code by using regular expressions. Just give it a try!

Leave a Reply

Your email address will not be published. Required fields are marked *