inicio mail me! sindicaci;ón

HTML5 input validation with custom message

HTML5 provides us with ways to specify different types of input, complete with client side validation. Inputs can be marked as required and it is even possible to specify regexp patterns for valid input.

Let’s put this into action by creating an input for german zip codes, consisting of 5 numbers:

As you can see, this works, but the actual validation message you get when entering a wrong code is a bit generic (In german: „Ihre Eingabe muss mit dem geforderten Format übereinstimmen.“). Instead, you would want the message to state what a correct zip code has to look like.

Fortunately there is a way to specify the message to be displayed via the javascript setCustomValidity method (unfortunately there is no way to do this via another attribute, say pattern-invalidmessage).

Now, when using the setCustomValidity method there is a conceptual problem. Setting this on an input field, automatically renders this field invalid, no matter whether it is otherwise perfectly fine!

So for our case, we want to set this message only after the browser has decided, that the field does not match the pattern, kind of as a second error on the field. The message should be specified in another attribute called data-invalidmessage.
The following CoffeeScript does just that:

The final working example:

Schreibe einen Kommentar