How to use validationMessage
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:
Let’s explain line by line
- We get the element with the form tag and the element with the id #message
- To the form element we listen to the input event, this will be fired when the user writes in any of the <input> children.
- When the event is triggered we call the function addMessage
- The addMessage function receives the event in the parameter e
- Inside the event we look for the target and inside the validationMessage
- 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.