Skip to content

Instantly share code, notes, and snippets.

@Microtribute
Created April 2, 2020 18:10
Show Gist options
  • Save Microtribute/2aa98994feea8a07e27360bb9271e69a to your computer and use it in GitHub Desktop.
Save Microtribute/2aa98994feea8a07e27360bb9271e69a to your computer and use it in GitHub Desktop.
Reject non-numeric values from input[type=number] elements
<!-- SUMMARY:
INPUT[type=numer] elements may accept illegal values which are not a number depending on the browser you're using.
This is a known issue in Firefox.
This demo is to prevent users from entering illegal values.
-->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Demo</title>
</head>
<body>
<!-- INPUT type=number -->
<input type="number" value="0" step="1">
<div>23.343424</div>
<div>3.</div>
<div>abcdefg</div>
<script>
var field = document.querySelector('input[type="number"]');
// When you edit the input manually by typing.
field.onkeypress = function (e) {
return 1 === e.key.length ? (/^\d$/.test(e.key) || ('.' === e.key && !/\./.test(this.value))) : true;
};
// When you drag & drop or paste a text from another source to the element.
field.ondrop = field.onpaste = function () {
setTimeout(function () {
if (field.value === '') {
field.value = '';
field.focus();
}
}, 50);
};
// Once the focus moves out of the element, the value gets corrected.
field.onblur = function (e) {
if (this.value.startsWith('.')) { // .3332
this.value = '0' + this.value;
} else if (this.value.endsWith('.')) { // 332.
this.value = this.value.slice(0, -1);
}
};
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment