5

Assume abstract validator callback that returns true of false depending on whether new string value is valid:

function isValid(text) {
   /* arbitrary code, returns true or false */
}

I want to apply this callback in input field in HTML/JavaScript. The code in the validator can be any kind of validator.

I've seen people use keyup event to prevent some characters to be entered. This is flawed method and obviously cannot validate whole input field.

I tried to cancel input event, that doesn't work:

  myInputField.addEventListener("input", function(e) {
    console.log(e);
    e.preventDefault();
    return false;
  });

In most GUI frameworks I encountered (Java Swing, C++ Qt) this was as simple as assigning validator callback on the input field. How do I do this in JavaScript?

Tomáš Zato
  • 50,171
  • 52
  • 268
  • 778
  • I think I'm missing something, but what about just `if(isValid(this.value)) e.preventDefault();` – Washington Guedes May 12 '16 at 15:50
  • 1
    @user6188402 You're missing an attempt to test that code to see that `input` event can't be canceled. – Tomáš Zato May 12 '16 at 15:52
  • But doesn't `input` fire after the text changed? You should probably want to use `keydown` and `isValid(this.value + String.fromCharCode(e.keyCode))` – Washington Guedes May 12 '16 at 15:55
  • @user6188402 What if the carret is in the middle of the field? What if the text is selected? What if pressed key is arrow or backspace? What if user uses cut or paste? What if user drags text in the field? – Tomáš Zato May 12 '16 at 16:12
  • Then, I would say to save the previous string, and if the new one is not valid, set it back to the previous one. In this case, you can continue using `input` event – Washington Guedes May 12 '16 at 16:14
  • You are right, there would be a lot of things to treat... Why not then, use `blur`, and after that, if the value is wrong shows a red label or anything like that? – Washington Guedes May 12 '16 at 16:26
  • Or, if you are going to replace content by the last valid input as I said, you should probably be able to set the cursor position using this [another answer](http://stackoverflow.com/a/12518737/6188402) and to get where the user was when [typing](http://stackoverflow.com/a/263796/6188402) – Washington Guedes May 12 '16 at 16:35
  • I need to make sure user simply cannot enter invalid value. The validator rules are complex - more close to script syntax than simple value - so it's best to prevent syntax errors from appearing, rather than prompting user to fix them. – Tomáš Zato May 12 '16 at 17:17

0 Answers0