1

Is there an eloquent way to restrict an input element to type a specific string?

The user should be able to press any key but only if the key matches the next correct char in the specific string should the input be accepted and the cursor advance.

There is the pattern attribute of course but I don't think that is the solution.

lukkea
  • 3,606
  • 2
  • 37
  • 51
  • set oninputchange on the input element, match the string with the input that you don't wanna allow and if it matches, disable the submit btn or something you might wanna do, say display an error message and clear the input field – Arunava May 01 '17 at 02:17
  • Can you explain a little more about what your expected behavior is? Should the user be able to type in only the specific string? – Hydrothermal May 01 '17 at 02:35
  • The user can technically press whatever key but only if the key matches the next correct char in the string should the cursor advance. Does that make sense? – Casey Caruso May 01 '17 at 03:09
  • 1
    The description makes sense. But I'm curious why you would want that behaviour? – nnnnnn May 01 '17 at 03:38
  • Why not just use an input with a preset value and set it to `disabled`? – Wesley Smith May 01 '17 at 04:18
  • If you're trying to test if the user typed in a correct value, like a coupon code or something, that is generally done after the user stops typing, clicks a button, or moves away from the field rather than on each keyup. And depending on the functionality, you may want to do the evaluating on the backend. Front end validation of a coupon code for example, would be quite silly. – Wesley Smith May 01 '17 at 04:31
  • I am looking to force a user to type a string for typing practice – Casey Caruso May 01 '17 at 05:53
  • This is a good first question; I edited earlier it to include the contents of a comment you made because that comment further clarified what you are trying to do. You can always edit your own question and refer the person who asked the question in the comments to your edit (using an @ such as @CaseyCaruso). You might want to take a look at [this question](http://stackoverflow.com/questions/5571514/convert-to-uppercase-as-user-types-using-javascript), it doesn't answer your query exactly but the principles should be the same, so it might help. – lukkea May 01 '17 at 11:59

1 Answers1

0

you could prevent default on the keydown if the entered key does not match your string. for instance:

const input = document.getElementById('omg')
const string = 'lolwow'
input.addEventListener('keydown', event => {
  const index = input.value.length
  if (string[index] != event.key) {
    event.preventDefault()
  }
})
chee
  • 26
  • 3