Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
147
rated 0 times [  151] [ 4]  / answers: 1 / hits: 15542  / 11 Years ago, tue, june 18, 2013, 12:00:00

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.


More From » jquery

 Answers
16

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();
}
}

[#77569] Monday, June 17, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
billtreytonb

Total Points: 211
Total Questions: 104
Total Answers: 114

Location: Sudan
Member since Tue, Aug 3, 2021
3 Years ago
;