How to manually report an input tag to the user via JS?

Viewed 42

Basically I want to create an effect like the one you get with required attributes: an example of the required attribute

(example from w3schools.com)

But since I'm not able to use something like type="email", because my patterns differ (and sometimes the input is used to add elements to an array), I want to check the validity manually via JavaScript and, if the inputted data isn't right, report it to the user as shown above.

Any ideas how to do it are highly appreciated!

2 Answers

Something like this might work.

const button = document.getElementById('btn') //use id of the button
button.addEventListener('click', handleButtonClick);
function handleButtonClick() {
   const inputValue = document.getElementById('input').value
   if (inputValue != null || inputValue !== '') {
      //do your logic here
   }
}

You can use oninvalid and onvalid

<input id="username"  type="text" required="required"
       oninvalid="this.setCustomValidity('Your alert')"
       onvalid="this.setCustomValidity('')">
Related