Add delete button and arrows to regex

I am checking the date, and now I am doing that the user can only enter numbers , / and backspace , so now I want to add 2 more keys to my regular expression. I want to add delete and arrow keys so that the changes change in my regex. 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.

+7
source share
3 answers

You can skip input validation if the arrow, delete, and backspace keys have been 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(); } } 
+9
source

you must use onkeyup to change and change the strength to check the current value.

errors:

1- your regular expression should be the opposite, your current one checks if any of them contains a value, but you want your value to have no other value.

2- you should avoid the slash character (/), like this \\, so that it is not taken as the end of the regular expression, and the rest becomes a modifier!

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 check the whole date as dd / mm / yyyy or whatever your format, just before you exist

+1
source

Why don't you just check the actual value of the element, and not the keys that create the value?

You can use the oninput event for oninput .

-one
source

All Articles