My goal is to create a form with fields that have real-time validation using JavaScript.
I have achieved this by utilizing Java events in the following way:
Text field
onkeyup: This event sends a request to check for errors in the field every time a key is released. If there are errors, they will be displayed; otherwise, an "Ok!" message will appear.
Submit button
onclick: When clicked, this event will once again check for errors. If any errors are found, they will be shown; otherwise, the submit button will be hidden.
Additionally, at the bottom of the page, I have included JavaScript code that automatically focuses on a Text Field when it appears.
By using both onkeyup and focus events on the field, after submitting the form without clicking the button (as the button event only triggers upon click, not when the 'enter' key is used), the focus event will automatically trigger the onkeyup event: this means that two events are called after submitting (focus implies onkeyup) resulting in displaying any errors first, if present, followed by the "Ok!" message.
I want to prevent focusing on the field after submitting the form so that the onkeyup event isn't triggered, unless the 'enter' key is used to simulate the 'click' of the submit button.
P.S.: If you have knowledge of other techniques for achieving real-time validation (and better ones), please share them with me.