There are 2 possible solutions:
CSS Method
To avoid the 'jump' behavior, you can increase the width of your input slightly. Example: width : 202px
View CSS solution on JSFiddle
JavaScript Approach
If adjusting the width is not an option, you can prevent the keypress event and check the length of the input value. If it is less than 4 characters, allow the input; otherwise, do nothing.
Using jQuery:
var t = $('#input-form');
t.keypress( function(event){
//Prevent the value from being added
event.preventDefault();
//Regex to determine allowed characters (alphanumeric & underscore in this case)
var reg = /\w/g;
//Get the key pressed
var inputChar = String.fromCharCode(event.which);
//Get the length of the input's value
var inputLength = t.val().length;
if ( reg.test(inputChar) && (inputLength < 4) ) {
//Add the value if input length is less than 4
t.val(t.val() + inputChar);
}else{
//Do nothing if conditions are not met
return;
}
});
View jQuery solution on JSFiddle
Pure JavaScript Method:
var t = document.getElementById('input-form');
t.addEventListener('keypress', function(event){
//Prevent the value from being added
event.preventDefault();
//Regex to determine allowed characters (alphanumeric & underscore in this case)
var reg = /\w/g;
//Get the key pressed
var inputChar = String.fromCharCode(event.which);
//Get the length of the input's value
var inputLength = t.value.length;
if ( reg.test(inputChar) && (inputLength < 4) ) {
//Add the value if input length is less than 4
t.value = t.value + inputChar;
}else{
//Do nothing if conditions are not met
return;
}
});
View Pure JavaScript solution on JSFiddle