1

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

1 Answer 1

1

You can use javasript checkValidity() to trigger validate.

form.addEventListener('submit', async (e)=>{
    e.preventDefault()
    e.target.checkValidity(); //this check
    let isValid = await isUserValid(usernameInput)
    console.log(isValid)
})
Sign up to request clarification or add additional context in comments.

9 Comments

Thank you. isUserValid does asynchronously check the users validity, so I don't know if the user is valid until I performed that check (but then I know, so I don't need checkValidity anymore). checkValidity however does only return true or false, it does not let the validity message appear. I just found out that reportValidity() does also show the validity message.
So what do you want to fix other than this ?
Please see for yourself: codepen.io/MartinMuzatko/pen/eEvyYK?editors=1010 and media.giphy.com/media/l41K48Jb6rbT9SxSE/giphy.gif The validity is delayed, correct values can't be submitted - because the validation check is delayed and the submit event is not fired when the input is invalid.
Also, if I blur the input element and then want to submit, I can't, because I call preventDefault. So I have to remove the form event handler when the value is correct?
@MartinMuzatkoK15tSoftware I think that you want to use keypress event to check everytime that user press a key to check validity
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.