I want the user to input a number with format:
##/####
Where the "#" are numbers.
Here is the sample code:
(function() {
var previousValue = document.getElementById('myInput').value;
var pattern = /^\d{2}(\/\d{4})?$/;
function validateInput(event) {
event = event || window.event;
var newValue = event.target.value || '';
if (newValue.match(pattern)) {
// Valid input; update previousValue:
previousValue = newValue;
} else {
// Invalid input; reset field value:
event.target.value = previousValue;
}
}
document.getElementById('myInput').onkeyup = validateInput;
}());
<input id="myInput" type="text" maxlength=7 value="" />
I can only write the first two numbers, but I can't type anything else after that, even though the regular expression seems correct to me.
---EDIT---
After all the answers, I want to point out that I already have a validator that fires on the submit, which tells the user if they have typed in the correct form; I just wanted to somehow "guide" the user in the typing of the input.