views:

140

answers:

2
/^[a-d][a-d]*(?:_[a-d]+)*$/

I'm using the above regex in jquery where I call it on every keypress on an input field. It works exactly as intended which is a problem because I'm running a dynamic update too. You can tell for yourself what it does, but the point here is the underscore _. It's meant to be followed by a character a-d and therefore cannot be the last thing the user types. This is my problem.

Since the regex is being checked against something that's being typed (in progress), it's not being checked against the final version. With every keypress, I check the validity of the regex, and if no match, I remove the offending character (instantly, the user can't get to see it, it doesn't register in the input field). This means that if the user types some_, the dynamic correction kicks in and takes it back to some (even if the user is in the middle of typing a continuation.

Is there any way I can slow down the keypress or any other solution in this case?

A: 

You could use a timeout to wait for a delayed time, and cancel the timeout after a new keypress, however I don't think that's the right approach. Perhaps you should only check for the underscore (or the absence of any terminating character) on the blur() event, rather than the keypress. This would indicate that the user is done typing.

Alex Sexton
+1  A: 

If I am reading this right then you want the each character to display on the screen then be removed you might want to use the onkeyup event instead of the onkeypress. As alex suggested you could add

setTimeout ( expression, timeout );

To delay calling the code, depends exactly what you are after really.

Dean