I want to let users only submit the form, when the user does not exist already. For that I built a little rest api to check if the typed in user already exists on input blur or form submit. This works
The trickiest part is about setting the custom validity. I want to use native form validation and error handling as much as possible. So I dynamically set and unset the pattern attribute.
Problem 1: The message of the invalid input is not displayed when submitting the form by pressing enter (Can I manually trigger the form to display the validity message?)
Problem 2: When entering an invalid name, submit and then enter a valid name and submit again, the validation error message appears shortly, then disappears. (Since preventDefault has to be called synchronously, should I re-submit the form when the input is valid and remove the eventlistener for submit, so the form gets submit?
I prepared a little codepen to share with you: https://codepen.io/MartinMuzatko/pen/BdWmBg?editors=1010
This is the code concerning my problems:
usernameInput.addEventListener('blur', async (e)=>{
let isValid = await isUserValid(e.target)
console.log(isValid)
})
form.addEventListener('submit', async (e)=>{
e.preventDefault()
let isValid = await isUserValid(usernameInput)
console.log(isValid)
})
Thank you in advance!
Best, Martin