I have a simple implementation of some “real time” validation for an input. The allowed characters are lower and uppercase alpha, 0-9, hyphens, period, apostrophe, and spaces. The field is limited to 15 characters. I’m using jQuery here simply for ease of use in my example, it may or may not be used for my project.
Currently when trying to place/move the cursor within the input using the arrow keys I’m always taken to the end of the string. The same happens when trying to select all text using keys (CTRL-A). Is there a better way of accomplishing what I’m looking for that avoids this? It seems like poor user experience to me.
$( '#sample' ).on( 'keyup', function( event ) {
var str = $( this ).val();
str = str.replace(/[^A-Za-z-0-9.'\s]/g, "").substring(0,15);
$( this ).val( str );
});
I also have a jsFiddle set up here
Most of the issues can be preventent just by updating the input value only if it actually changes.
To solve removing characters from the middle of the text you need to remember and reset caret position. For that you can use following functions:
And extend your keyup handler:
See updated FIDDLE.