Last active
March 12, 2019 12:38
-
-
Save rkeVader/e75c595278caf2185d21a0488113b405 to your computer and use it in GitHub Desktop.
html text input validators for Floating Point and Integers... BETA - threw together for quick-n-dirty job.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// prevent non-floating points from being typed | |
// pressed key must either be a number, | |
// or a decimal point (only if one has not already been typed) | |
// or a negative sign (only we are at the start of the input) | |
// USAGE: | |
// <input type="text" onkeypress="return isFloatingPoint(event);" /> | |
function isFloatingPoint(evt) | |
{ | |
var nochars = evt.currentTarget.value.trim().length == 0; | |
var alreadyHasDecimal = evt.currentTarget.value.indexOf(".") >= 0; | |
var charCode = (evt.which) ? evt.which : event.keyCode | |
if (charCode == 45 && nochars) | |
return true; | |
else if (charCode == 45 && !nochars) | |
return false; | |
if (charCode == 46 && !alreadyHasDecimal) | |
return true; | |
else if (charCode == 46 && alreadyHasDecimal) | |
return false; | |
else if (charCode > 31 && (charCode < 48 || charCode > 57)) | |
return false; | |
else | |
return true; | |
} // isFloatingPoint validator | |
// prevent non-integer points from being typed | |
// pressed key must either be a number | |
// or a negative sign (only we are at the start of the input) | |
// USAGE: | |
// <input type="text" onkeypress="return isInteger(event);" /> | |
function isInteger(evt) { | |
var nochars = evt.currentTarget.value.trim().length == 0; | |
if (!nochars && evt.currentTarget.selectionStart !== undefined) { | |
// standards-compliant version | |
var startPos = evt.currentTarget.selectionStart; | |
var endPos = evt.currentTarget.selectionEnd; | |
if (startPos == 0 && endPos == 0) { | |
nochars = true; | |
} else if (evt.currentTarget.value.substring(0, 1) != "-") { | |
nochars = true; | |
} | |
} | |
var charCode = (evt.which) ? evt.which : event.keyCode | |
if (charCode == 45 && nochars) | |
return true; | |
else if (charCode == 45 && !nochars) | |
return false; | |
else if (charCode > 31 && (charCode < 48 || charCode > 57)) | |
return false; | |
else | |
return true; | |
} // isInteger validator |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment