I am implementing a feature where users can only submit the form if the user does not already exist. To achieve this, I have created a custom rest API to check if the entered user already exists either on input blur or form submission. This approach has been successful so far.
The most challenging aspect is setting the custom validity for error handling. My goal is to leverage native form validation and error handling functionalities as much as possible. Therefore, I dynamically set and unset the pattern attribute accordingly.
Issue 1: When submitting the form by pressing enter, the message for invalid input is not displayed. (Is there a way to manually trigger the form to display the validity message?)
Issue 2: Upon entering an invalid name, submitting, then correcting it to a valid name and submitting again, the validation error message briefly appears and then disappears. (Considering that preventDefault must be called synchronously, should I re-submit the form when the input is valid and remove the event listener for submit to allow the form to be submitted?)
I have prepared a codepen to demonstrate the scenario: https://codepen.io/MartinMuzatko/pen/BdWmBg?editors=1010
The following code addresses my concerns:
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)
})
Your assistance is greatly appreciated!
Sincerely, Martin