javascripthtmlvalidationoperaconstraint-validation-api

Any workaround of Opera 12's input type=number validity behavior?


I was just troubleshooting an issue with a library of mine but it boils down to being something related with Opera behavior. Now, I haven't found big warnings anywhere on this issue, so my guess is that I'm missing something, or that there's a workaround that I just don't know of.

Specifically, take a simple code like this:

<input type="number" id="myNumber" />

On Opera 12.16, the input type=number is supported, so it'll correctly display a type=number input.

If the user enters a valid value, say "123", then:

var myInput = document.getElementById('myNumber');
myInput.value // => "123"
myInput.validity // => { valid: true, typeMismatch: false, ... }
myInput.validity.badInput // undefined

Now, if the user enters "123a", then:

var myInput = document.getElementById('myNumber');
myInput.value // => ""
myInput.validity // => { valid: true, typeMismatch: false, ... } -- why valid: true?
myInput.validity.badInput // undefined

Furthermore: myInput.willValidate returns true and myInput.checkValidity() returns true as well.

So, how can I actually check for bad input in input type=number on this version of Opera? (Consider an empty string is and should be valid input.)


Solution

  • element.focus();
    document.execCommand("SelectAll");
    window.getSelection().focusNode.selectionStart;
    

    This returns the length of the text entered in the input. Using it you can distinguish between an empty input and an invalid value. Remember to add an exception for tab.