Related
Using <input type=number> will cause this.value inside of an event listener to return an empty string if the input is not a valid number. You can see an example of this at http://jsfiddle.net/fSy53/
However, the invalid characters are still displayed in the input.
Is there any way to get the value that is actually displayed, including the invalid characters, from within an event listener?
My ultimate goal is to prevent users from actually typing any non-numeric characters into the field. I need to use type=number so that the numeric virtual keyboard is used by mobile devices. My goal would be to do something like this.value = this.value.replace(/[^0-9.]/g, "") on keyup keypress, but this doesn't work because if an invalid character is typed, reading from this.value returns "".
Try preventing the default behaviour if you don't like the incoming key value:
document.querySelector("input").addEventListener("keypress", function (evt) {
if (evt.which < 48 || evt.which > 57)
{
evt.preventDefault();
}
});
You can accomplish this by preventing the keyPress event from occurring for non-numeric values
e.g (using jQuery)
$('.input-selector').on('keypress', function(e){
return e.metaKey || // cmd/ctrl
e.which <= 0 || // arrow keys
e.which == 8 || // delete key
/[0-9]/.test(String.fromCharCode(e.which)); // numbers
})
This accounts for all different types of input (e.g. input from the number pad has different codes than the keyboard) as well as backspace, arrow keys, control/cmd + r to reload etc
Please note that e.which, e.keyCode and e.charCode are deprecated: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/which
I prefer e.key:
document.querySelector("input").addEventListener("keypress", function (e) {
var allowedChars = '0123456789.';
function contains(stringValue, charValue) {
return stringValue.indexOf(charValue) > -1;
}
var invalidKey = e.key.length === 1 && !contains(allowedChars, e.key)
|| e.key === '.' && contains(e.target.value, '.');
invalidKey && e.preventDefault();});
This function doesn't interfere with control codes in Firefox (Backspace, Tab, etc) by checking the string length: e.key.length === 1.
It also prevents duplicate dots at the beginning and between the digits: e.key === '.' && contains(e.target.value, '.')
Unfortunately, it doesn't prevent multiple dots at the end: 234....
It seems there is no way to cope with it.
The other answers seemed more complicated than necessary so I adapted their answers to this short and sweet function.
function allowOnlyNumbers(event) {
if (event.key.length === 1 && /\D/.test(event.key)) {
event.preventDefault();
}
}
It won't do change the behavior of any arrow, enter, shift, ctrl or tab keys because the length of the key property for those events is longer than a single character. It also uses a simple regular expressions to look for any non digit character.
inputs[5].addEventListener('keydown', enterNumbers);
function enterNumbers(event) {
if ((event.code == 'ArrowLeft') || (event.code == 'ArrowRight') ||
(event.code == 'ArrowUp') || (event.code == 'ArrowDown') ||
(event.code == 'Delete') || (event.code == 'Backspace')) {
return;
} else if (event.key.search(/\d/) == -1) {
event.preventDefault();
}
}
in this case, the value of the input field stays intact when a non-number button is pressed, and still delete, backspace, arrowup-down-left-right work properly and can be used for modifying the digital input.
This solution seems to be working well for me. It builds on #pavok's solution by preserving ctrl key commands.
document.querySelector("input").addEventListener("keypress", function (e) {
if (
e.key.length === 1 && e.key !== '.' && isNaN(e.key) && !e.ctrlKey ||
e.key === '.' && e.target.value.toString().indexOf('.') > -1
) {
e.preventDefault();
}
});
I will add MetaKey as well, as I am using MacOS
input.addEventListener("keypress", (e) => {
const key = e.key;
if (!(e.metaKey || e.ctrlKey) && key.length === 1 && !/\d\./.test(key)) {
e.preventDefault();
}
}
Or, you can try !isNaN(parseFloat(key))
try this one :
current key pressed -> e
if e is not a number -> isNaN(e.key)
when condition is true , so default action should not be taken as it normally would be -> e.preventDefault()
else, return default action... e
input.addEventListener("keypress", function (e) {
if (isNaN(e.key)) e.preventDefault();
});
Update on the accepted answer:
Because of many properties becoming deprecated
(property) KeyboardEvent.which: number #deprecated
you should just rely on the key property and create the rest of the logic by yourself:
The code allows Enter, Backspace and all numbers [0-9], every other character is disallowed.
document.querySelector("input").addEventListener("keypress", ({ key, preventDefault }) => {
if (isNaN(parseInt(key, 10)) && !['Backspace', 'Enter'].includes(key)) {
preventDefault();
}
});
NOTE
This will disable paste action
Based on Nrzonline's answer: I fixed the problem of the multiple "." at the end of the input by adding a
let lastCharacterEntered
outside of the input and then onKeyPress
e => {
var allowedChars = "0123456789.";
function contains(stringValue, charValue) {
return stringValue.indexOf(charValue) > -1;
}
var invalidKey =
(e.key.length === 1 && !contains(allowedChars, e.key)) ||
(e.key === "." && contains(e.target.value, "."));
console.log(e.target.value);
invalidKey && e.preventDefault();
if (!invalidKey) {
if (lastCharacterEntered === "." && e.key === ".") {
e.preventDefault();
} else {
lastCharacterEntered = e.key;
}
}
}
I just had the same problem and discovered an alternative solution using the validation API - works without black magic in all major browsers (Chrome, Firefox, Safari) except IE. This solution simply prevents users from entering invalid values.
I also included a fallback for IE, which is not nice but works at least.
Context: onInput function is called on input events, setInputValue is used to set the value of the input element, previousInputValue contains the last valid input value (updated in setInputValue calls).
function onInput (event) {
const inputValue = event.target.value;
// badInput supported on validation api (except IE)
// in IE it will be undefined, so we need strict value check
const badInput = event.target.validity.badInput;
// simply prevent modifying the value
if (badInput === true) {
// it's still possible to enter invalid values in an empty input, so we'll need this trick to prevent that
if (previousInputValue === '') {
setInputValue(' ');
setTimeout(() => {
setInputValue('');
}, 1);
}
return;
}
if (badInput === false) {
setInputValue(inputValue);
return;
}
// fallback case for IE and other abominations
// remove everything from the string expect numbers, point and comma
// replace comma with points (parseFloat works only with points)
let stringVal = String(inputValue)
.replace(/([^0-9.,])/g, '')
.replace(/,/g, '.');
// remove all but first point
const pointIndex = stringVal.indexOf('.');
if (pointIndex !== -1) {
const pointAndBefore = stringVal.substring(0, pointIndex + 1);
const afterPoint = stringVal.substring(pointIndex + 1);
// removing all points after the first
stringVal = `${pointAndBefore}${afterPoint.replace(/\./g, '')}`;
}
const float = parseFloat(stringVal);
if (isNaN(float)) {
// fallback to emptying the input if anything goes south
setInputValue('');
return;
}
setInputValue(stringVal);
}
Prevent typing non-Alphabet in specific input id for pages that have more than one input item.it's usable for Oracle Apex developers
--- Append in HTML header of page
<script type="text/javascript">
function validateNumber(event) {
const activeElmnt = document.activeElement;
var keyCode = event.keyCode;
var excludedKeys = [8, 37, 39, 46];
if ( activeElmnt.id == "input id in HTML page"){
if (!((keyCode >= 65 && keyCode <= 90) ||
(keyCode >= 97 && keyCode <= 122) ||
(excludedKeys.includes(keyCode)))) {
console.log("alphabets are not allowed");
event.preventDefault();
}
}
console.log("keycode: " + keyCode + "ActiveElemet: "+activeElmnt.id);
}
</script>
-- Append in page HTML Body attribute
onkeydown="validateNumber(event);"
here is my simple solution simply
in this solution u should keep the input type to text so when you use event.target.value you get the full string not only the numbers or an empty string instead so you actually can check if there is a point yet or not.
and i didn't use the deprecated properties event.which
isNumber(event) {
var allowed = "";
if (event.target.value.includes(".")) {
allowed = "123456789";
} else {
allowed = "123456789.";
}
if (!allowed.includes(event.key)) {
event.preventDefault();
}
}
document.getElementById('number').addEventListener('keypress', isNumber);
the HTML
```
function isNumber(event) {
var allowed = "";
if (event.target.value.includes(".")) {
allowed = "0123456789";
} else {
allowed = "0123456789.";
}
if (!allowed.includes(event.key)) {
event.preventDefault();
}
}
document.getElementById('number').addEventListener('keypress',isNumber);
<h3>You can input only numbers and one point (this would be a float or int) </h3>
<input type="text" id="number" />
This one should work. Only works with integers.
function validateNumberInput(e) {
if (isNaN(e.key)) {
e.preventDefault();
}
}
You can however implement floats with few more lines:
function validateNumberInput(e) {
if (isNaN(e.key) && e.key !== '.') {
e.preventDefault();
} else if (e.key === '.') {
if (e.target.value.indexOf('.') >= 0) {
e.preventDefault();
}
}
}
Finally use it like:
targetInput.addEventListener('keypress', function (e) {
validateNumberInput(e);
});
A very nice react solution... You just want to consume the event if its NaN
onKeyedPress = (e) => {
if(!parseInt(e.key)){
e.preventDefault();
}
}
Try it:
document.querySelector("input").addEventListener("keyup", function () {
this.value = this.value.replace(/\D/, "")
});
I need a field which can only take numbers, but not allow for signs such as "+", "-", "*" and "/". 0 can also not be the first number. If I make an Input field and set it's type to "number" I'm still allowed to write at least "+" and "-", and I can't quite seem to prevent the user from writing 0 as the first number either.
$('input#update-private-ext').on('keydown', function (e) {
var value = String.fromCharCode(e.keyCode);
if ($(this).text.length == 0 && value == 0) {
return false;
}
});
The above was my first attempt at making the function disallow 0 as the first character, but it doesn't seem to work. It just lets me write 0 as the first character. I also tried this to stop the signs from showing up:
$('input#update-private-ext').on('keydown', function (e) {
var badChars = '+-/*';
var value = String.fromCharCode(e.keyCode);
if ($(this).text.length == 0 && value == 0) {
return false;
}
if (badChars.indexOf(value) == -1) {
return false;
}
});
But with the badChars check, I cannot write anything in my field. So what am I missing here?
You should use e.key to get the current key pressed. String.fromCharCode(e.keyCode) gives the wrong result.
Also you should check if the bad chars is not -1. If it is, then your char is not a bad character and so you should not enter the if.
If you want to get the length of the input field you should use jQuery's .val() and not .text(). Or you can simply do it without jQuery using this.value.length.
$('input#update-private-ext').on('keydown', function (e) {
var badChars = '+-/*';
var value = e.key;
if (this.value.length == 0 && value == '0') {
return false;
}
if (badChars.indexOf(value) !== -1) {
return false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="update-private-ext">
When you compare numbers and strings you must remember that numbers are encoded by using character codes from 48 to 57 and comparing strings with numbers is error-prone in JavaScript as there are many implicit coercions. You should be comparing objects of the same type to avoid the confusion.
In your case, the comparison should be done in the way that parsed string from the String.fromCharCode equals '0' - zero character (string), not the 0 as a number.
There are also issues of the keyCode parsing which yield strange values for the symbols because you would have to manually consider if Shift and other meta keys are pressed when parsing. Save yourself a trouble and just use e.key to get parsed key value.
By the way, please see the difference between this and $(this). Basically, in your case, it means that real instance of the input field is the first element of JQuery iterator - $(this)[0]. You may then just use this, which is automatically set to the target element in the event handler.
Please see the following example of blocking first 0 with debug information printed out:
$('input#update-private-ext').on('keydown', function (e) {
var value = e.key;
console.log('Typed character:');
console.log(value);
console.log('$(this)');
console.log($(this));
console.log('this (input element):');
console.log(this);
console.log("input's value:");
console.log(this.value);
if (this.value.length == 0 && value == '0') {
console.log('blocked');
return false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="update-private-ext" />
In order to block other characters you can just filter them the following way (remember that indexOf returns -1 when the index is not found):
$('input#update-private-ext').on('keydown', function (e) {
var badChars = '+-/*';
var value = e.key;
if (this.value.length == 0 && value == '0') {
return false;
}
//Please note NOT EQUALS TO -1 which means not found.
if (badChars.indexOf(value) !== -1) {
return false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="update-private-ext" />
You can do something like this below:
1. Check for bad chars if badChars.indexOf(v) >= 0.
2. Disallow starting from 0 by checking if the input starts from 0 and if yes, set the input field to blank.
This can give you a start!
$('input#update-private-ext').on('keydown', function(e) {
var badChars = '+-/*';
var v = e.key;
if (badChars.indexOf(v) >= 0) {
return false;
}
if ($(this).val().startsWith('0')) {
$(this).val("");
return false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="update-private-ext" />
I have been trying to allow numeric field and one decimal point in my Grid.Its work fine when its suitable for input box.
when i am calling onKeyPress the script work fine for "input box" rather than on "Div element"
In "Div element",when i am supposed to use this .It allow to access only for number rather Alphabet
hence,while coming to "decimal place" its not working as it should.[ It's allowing many Dot's]
<script>
function getKey(e)
{
if (window.event)
return window.event.keyCode;
else if (e)
return e.which;
else
return null;
}
function restrictChars(e, obj)
{
var CHAR_AFTER_DP = 2; // number of decimal places
var validList = "0123456789."; // allowed characters in field
var key, keyChar;
key = getKey(e);
if (key == null) return true;
// control keys
// null, backspace, tab, carriage return, escape
if ( key==0 || key==8 || key==9 || key==13 || key==27 )
return true;
// get character
keyChar = String.fromCharCode(key);
// check valid characters
if (validList.indexOf(keyChar) != -1)
{
// check for existing decimal point
var dp = 0;
if( (dp = obj.value.indexOf( ".")) > -1)
{
if( keyChar == ".")
return false; // only one allowed
else
{
// room for more after decimal point?
if( obj.value.length - dp <= CHAR_AFTER_DP)
return true;
}
}
else return true;
}
// not a valid character
return false;
}
</script>
<div onKeyPress="return restrictChars(event, this)">
Any Ideas how we could achieve it
For an <input>, it is required to check the value attribute, hence why obj.value is used in your code above. A div element doesn't have a value attribute. You have to check it's innerHTML (mdn docs). If you replace all instances of obj.value with obj.innerHTML, your code should work.
You need to use jQuery keypress() method to handle this right:
$("#d input").keypress(function(event){
return restrictChars(event);
});
See the working fiddle:
http://fiddle.jshell.net/ePvJ8/1/
Using <input type=number> will cause this.value inside of an event listener to return an empty string if the input is not a valid number. You can see an example of this at http://jsfiddle.net/fSy53/
However, the invalid characters are still displayed in the input.
Is there any way to get the value that is actually displayed, including the invalid characters, from within an event listener?
My ultimate goal is to prevent users from actually typing any non-numeric characters into the field. I need to use type=number so that the numeric virtual keyboard is used by mobile devices. My goal would be to do something like this.value = this.value.replace(/[^0-9.]/g, "") on keyup keypress, but this doesn't work because if an invalid character is typed, reading from this.value returns "".
Try preventing the default behaviour if you don't like the incoming key value:
document.querySelector("input").addEventListener("keypress", function (evt) {
if (evt.which < 48 || evt.which > 57)
{
evt.preventDefault();
}
});
You can accomplish this by preventing the keyPress event from occurring for non-numeric values
e.g (using jQuery)
$('.input-selector').on('keypress', function(e){
return e.metaKey || // cmd/ctrl
e.which <= 0 || // arrow keys
e.which == 8 || // delete key
/[0-9]/.test(String.fromCharCode(e.which)); // numbers
})
This accounts for all different types of input (e.g. input from the number pad has different codes than the keyboard) as well as backspace, arrow keys, control/cmd + r to reload etc
Please note that e.which, e.keyCode and e.charCode are deprecated: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/which
I prefer e.key:
document.querySelector("input").addEventListener("keypress", function (e) {
var allowedChars = '0123456789.';
function contains(stringValue, charValue) {
return stringValue.indexOf(charValue) > -1;
}
var invalidKey = e.key.length === 1 && !contains(allowedChars, e.key)
|| e.key === '.' && contains(e.target.value, '.');
invalidKey && e.preventDefault();});
This function doesn't interfere with control codes in Firefox (Backspace, Tab, etc) by checking the string length: e.key.length === 1.
It also prevents duplicate dots at the beginning and between the digits: e.key === '.' && contains(e.target.value, '.')
Unfortunately, it doesn't prevent multiple dots at the end: 234....
It seems there is no way to cope with it.
The other answers seemed more complicated than necessary so I adapted their answers to this short and sweet function.
function allowOnlyNumbers(event) {
if (event.key.length === 1 && /\D/.test(event.key)) {
event.preventDefault();
}
}
It won't do change the behavior of any arrow, enter, shift, ctrl or tab keys because the length of the key property for those events is longer than a single character. It also uses a simple regular expressions to look for any non digit character.
inputs[5].addEventListener('keydown', enterNumbers);
function enterNumbers(event) {
if ((event.code == 'ArrowLeft') || (event.code == 'ArrowRight') ||
(event.code == 'ArrowUp') || (event.code == 'ArrowDown') ||
(event.code == 'Delete') || (event.code == 'Backspace')) {
return;
} else if (event.key.search(/\d/) == -1) {
event.preventDefault();
}
}
in this case, the value of the input field stays intact when a non-number button is pressed, and still delete, backspace, arrowup-down-left-right work properly and can be used for modifying the digital input.
This solution seems to be working well for me. It builds on #pavok's solution by preserving ctrl key commands.
document.querySelector("input").addEventListener("keypress", function (e) {
if (
e.key.length === 1 && e.key !== '.' && isNaN(e.key) && !e.ctrlKey ||
e.key === '.' && e.target.value.toString().indexOf('.') > -1
) {
e.preventDefault();
}
});
I will add MetaKey as well, as I am using MacOS
input.addEventListener("keypress", (e) => {
const key = e.key;
if (!(e.metaKey || e.ctrlKey) && key.length === 1 && !/\d\./.test(key)) {
e.preventDefault();
}
}
Or, you can try !isNaN(parseFloat(key))
try this one :
current key pressed -> e
if e is not a number -> isNaN(e.key)
when condition is true , so default action should not be taken as it normally would be -> e.preventDefault()
else, return default action... e
input.addEventListener("keypress", function (e) {
if (isNaN(e.key)) e.preventDefault();
});
Update on the accepted answer:
Because of many properties becoming deprecated
(property) KeyboardEvent.which: number #deprecated
you should just rely on the key property and create the rest of the logic by yourself:
The code allows Enter, Backspace and all numbers [0-9], every other character is disallowed.
document.querySelector("input").addEventListener("keypress", ({ key, preventDefault }) => {
if (isNaN(parseInt(key, 10)) && !['Backspace', 'Enter'].includes(key)) {
preventDefault();
}
});
NOTE
This will disable paste action
Based on Nrzonline's answer: I fixed the problem of the multiple "." at the end of the input by adding a
let lastCharacterEntered
outside of the input and then onKeyPress
e => {
var allowedChars = "0123456789.";
function contains(stringValue, charValue) {
return stringValue.indexOf(charValue) > -1;
}
var invalidKey =
(e.key.length === 1 && !contains(allowedChars, e.key)) ||
(e.key === "." && contains(e.target.value, "."));
console.log(e.target.value);
invalidKey && e.preventDefault();
if (!invalidKey) {
if (lastCharacterEntered === "." && e.key === ".") {
e.preventDefault();
} else {
lastCharacterEntered = e.key;
}
}
}
I just had the same problem and discovered an alternative solution using the validation API - works without black magic in all major browsers (Chrome, Firefox, Safari) except IE. This solution simply prevents users from entering invalid values.
I also included a fallback for IE, which is not nice but works at least.
Context: onInput function is called on input events, setInputValue is used to set the value of the input element, previousInputValue contains the last valid input value (updated in setInputValue calls).
function onInput (event) {
const inputValue = event.target.value;
// badInput supported on validation api (except IE)
// in IE it will be undefined, so we need strict value check
const badInput = event.target.validity.badInput;
// simply prevent modifying the value
if (badInput === true) {
// it's still possible to enter invalid values in an empty input, so we'll need this trick to prevent that
if (previousInputValue === '') {
setInputValue(' ');
setTimeout(() => {
setInputValue('');
}, 1);
}
return;
}
if (badInput === false) {
setInputValue(inputValue);
return;
}
// fallback case for IE and other abominations
// remove everything from the string expect numbers, point and comma
// replace comma with points (parseFloat works only with points)
let stringVal = String(inputValue)
.replace(/([^0-9.,])/g, '')
.replace(/,/g, '.');
// remove all but first point
const pointIndex = stringVal.indexOf('.');
if (pointIndex !== -1) {
const pointAndBefore = stringVal.substring(0, pointIndex + 1);
const afterPoint = stringVal.substring(pointIndex + 1);
// removing all points after the first
stringVal = `${pointAndBefore}${afterPoint.replace(/\./g, '')}`;
}
const float = parseFloat(stringVal);
if (isNaN(float)) {
// fallback to emptying the input if anything goes south
setInputValue('');
return;
}
setInputValue(stringVal);
}
Prevent typing non-Alphabet in specific input id for pages that have more than one input item.it's usable for Oracle Apex developers
--- Append in HTML header of page
<script type="text/javascript">
function validateNumber(event) {
const activeElmnt = document.activeElement;
var keyCode = event.keyCode;
var excludedKeys = [8, 37, 39, 46];
if ( activeElmnt.id == "input id in HTML page"){
if (!((keyCode >= 65 && keyCode <= 90) ||
(keyCode >= 97 && keyCode <= 122) ||
(excludedKeys.includes(keyCode)))) {
console.log("alphabets are not allowed");
event.preventDefault();
}
}
console.log("keycode: " + keyCode + "ActiveElemet: "+activeElmnt.id);
}
</script>
-- Append in page HTML Body attribute
onkeydown="validateNumber(event);"
here is my simple solution simply
in this solution u should keep the input type to text so when you use event.target.value you get the full string not only the numbers or an empty string instead so you actually can check if there is a point yet or not.
and i didn't use the deprecated properties event.which
isNumber(event) {
var allowed = "";
if (event.target.value.includes(".")) {
allowed = "123456789";
} else {
allowed = "123456789.";
}
if (!allowed.includes(event.key)) {
event.preventDefault();
}
}
document.getElementById('number').addEventListener('keypress', isNumber);
the HTML
```
function isNumber(event) {
var allowed = "";
if (event.target.value.includes(".")) {
allowed = "0123456789";
} else {
allowed = "0123456789.";
}
if (!allowed.includes(event.key)) {
event.preventDefault();
}
}
document.getElementById('number').addEventListener('keypress',isNumber);
<h3>You can input only numbers and one point (this would be a float or int) </h3>
<input type="text" id="number" />
This one should work. Only works with integers.
function validateNumberInput(e) {
if (isNaN(e.key)) {
e.preventDefault();
}
}
You can however implement floats with few more lines:
function validateNumberInput(e) {
if (isNaN(e.key) && e.key !== '.') {
e.preventDefault();
} else if (e.key === '.') {
if (e.target.value.indexOf('.') >= 0) {
e.preventDefault();
}
}
}
Finally use it like:
targetInput.addEventListener('keypress', function (e) {
validateNumberInput(e);
});
A very nice react solution... You just want to consume the event if its NaN
onKeyedPress = (e) => {
if(!parseInt(e.key)){
e.preventDefault();
}
}
Try it:
document.querySelector("input").addEventListener("keyup", function () {
this.value = this.value.replace(/\D/, "")
});
I am performing date validation and now I am doing that user can only enter numbers ,/and backspace so now I want to add 2 more keys into my regular expression. I want to add delete and arrow keys so what will change I should do in my Regular Expression .This is my code
<input type="text" id="date" name="date" onkeypress="check(event,this);" />
this is me Javascript code
<script type="text/javascript">
function check(evt, id)
{
var value = id.value;
var theEvent = evt || window.event;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode( key );
var regex = /[0-9|\b|/]/;
if( !regex.test(key))
{
theEvent.returnValue = false;
if(theEvent.preventDefault)
theEvent.preventDefault();
}
}
</script>
Thanks waiting for your help.
You can skip the input validation if arrow, delete and backspace keys were pressed
function check(evt, id)
{
var value = id.value;
var theEvent = evt || window.event;
var key = theEvent.keyCode || theEvent.which;
// Don't validate the input if below arrow, delete and backspace keys were pressed
if(key == 37 || key == 38 || key == 39 || key == 40 || key == 8 || key == 46) { // Left / Up / Right / Down Arrow, Backspace, Delete keys
return;
}
key = String.fromCharCode( key );
var regex = /[0-9|/]/;
if( !regex.test(key))
{
theEvent.returnValue = false;
if(theEvent.preventDefault)
theEvent.preventDefault();
}
}
you should use on change and force change onkeyup to check the current value.
mistakes you have:
1- your regex should be the inverse, your current one checks if the value contains any of these but you want your value to not have other value.
2- you should escape the slash (/) character like this \/ so that it won't be assumed as the end of regex and the rest becomes modifiers!
Example:
document.getElementById('date').onchange = function(){
var regex = /[^\d\/]/g;
if(regex.test(this.value)) {console.log(false); return false;}
else {console.log(true); return true;}
};
document.getElementById('date').onkeyup = function(){
this.onchange();
};
DEMO
note: make sure you validate the whole date as dd/mm/yyyy or whatever your format is, right before sumission
Why don't you just check the actual value of the element, rather than the keypresses which create the value?
You can use the oninput event for that.