How to use validationMessage

Freddy Montes - Frontend Developer, Designer and TeacherFreddy Montes|

When validating forms we have to do a lot of logic to create the messages depending on the type of validation we are doing, but the browser has a built-in native system that works well for that.


The validationMessage property **** allows to obtain the validation message of a form element and it is native of the browser so it comes with translations by default.

To get this property we look for the element using querySelector and from that object we look for the validationMessage property.


We have the following form:

In this HTML it is important to highlight the type attribute of each <input> because based on this type is how the browser will do the corresponding validation:

Now the JavaScript code:

Let’s explain line by line

  1. We get the element with the form tag and the element with the id #message
  2. To the form element we listen to the input event, this will be fired when the user writes in any of the <input> children.
  3. When the event is triggered we call the function addMessage
  4. The addMessage function receives the event in the parameter e
  5. Inside the event we look for the target and inside the validationMessage
  6. If the validationMessage has a string, we add it to the DOM with the innerText of the #message element.

In this case when user enter any value to any of the <input> the input event will be fired and in the callback we will write in the DOM the validationMessage if any exists.



Thank your read this blog post. Any feedback or question hit me up on Twitter.

Tweet Me

Copyright © 2023. Design and code by myself with Next.js. Fork it and create yours