htmlvalidationconstraint-validation-api

HTML Validation: Using element.validity.typeMismatch and element.validity.tooLong


I have a JavaScript validation framework that I've created and I'm trying to add HTML validation to it. In my framework, validation is accomplished by binding validation-constraints to elements using a data- attributes. This is somewhat similar to how HTML validation happens by using attributes like required, min, max, etc.

I have two problems right now. Well, they may not necessarily be problems, but I would like a better understanding of the situation so that I can decide how to move forward.

The first issue I have element.validity.typeMismatch, which is set to true if the value of the element doesn't match the type of the element. For example, if you have an invalid URL value for an element with type="url" or an invalid email for an element with type="email". However, this behavior is inconsistent for something like type="number". The reason the behavior is inconsistent is because the browser won't let you add invalid values to an input with type="number" (through the UI or even through the DOM). Due to this, element.validity.typeMismatch is never set to true and element.checkValidity() always returns true. This behavior is inconsistent with the behavior on type="url" and type="email" where you can enter invalid values, and element.validity.typeMismatch and element.checkValidity() return the expected values.

I have a similar issue with using maxlength. There is a ValidityState property called tooLong at element.validity.tooLong. It appears that this value is never set to true when interacting with an input directly from the browser, because you can never enter a value that is longer than the value of* maxlength. Furthermore, even though you can set a value that is longer than maxlength from the DOM, element.validity.tooLong again, is never set to true. So I'm wondering why this property is even there if it is more-or-less useless.

Currently, how is HTML validation expected to behave with these constraints? How can an error message ever be generated for these constraint violations if the browser won't let you enter invalid values?


Solution

  • I was able to find more clarification on this matter. Both W3C and WHATWG say:

    typeMismatch

    The control is suffering from a type mismatch.

    [...]

    Suffering from a type mismatch

    When a control that allows arbitrary user input has a value that is not in the correct syntax (E-mail, URL).

    So it appears that this value is only set in the case of type being set to either url or email. In all other cases it will not be set because the input elements won't allow the user to set their values to invalid ones (manually or programmatically).

    Unfortunately, this doesn't answer the issue with tooLong; the specification says that this will be set if the input value is too long, but this doesn't seem to be the case.