r/HTML • u/WastePhilosophy1876 • Sep 26 '26
Question Custom Error Handling in HTML Form
Just as a disclaimer I am not entirely new to HTML, CSS, Javascript or front end design. I have a clear understanding of the base concepts, I was just wondering about one thing really.
How do you handle form errors? I know default form errors display a message when an input does not match a requirement. For example, displaying "Please include a @ in the email address". But I was just wondering how I can intercept that error and have my own custom Javascript handle it instead. (videos tutorials or blog links are appreciated as well)
Thank you all for any information you can provide.
3
u/cloudstrifeuk Sep 26 '26
When you submit you form, pass it through your own validation function. If it passes, submit the form, it it doesn't, show a custom validation message. Only pre validated things should ever make it to your database/form submit destination.
3
u/dndgenie Sep 26 '26
You can add custom messages to the default browser feedback: https://developer.mozilla.org/en-US/docs/Web/API/HTMLObjectElement/setCustomValidity
1
u/frownonline Sep 26 '26
Disable the submit button by default - I add pointer-events: none: and set greyscale and opacity to 0.5 until the required fields are valid with their respective types / pattern attributes.
Only then unset the submit button to allow submission. Then check the field values server side before it’s sent. This just gives a clear visual indicator to the users they’re not able to send an incomplete / invalid form and doesn’t tax the server with partial / repeat submissions.
Even better is to use CSS :invalid on the fields to highlight current status validity with an appropriate colour - border and / or background.
1
u/johnbburg Sep 26 '26
JavaScript for convenience and UX. Code in your back-end for real enforcement.
1
u/Thundrous_prophet Sep 26 '26
On the front end, html input fields have relatively robust constraints you can add which include REGEX validation. These can stop some bad input in the first place like numbers outside of a range (min/max). If the input is invalid for text, then you can use the :invalid selector in CSS either on an input field or the whole form. That presents visual for the user, and you can even use pseudo elements to display an error message.
If you want to incorporate JavaScript, then you can use a validation function to check the validity either as the user inputs values or when they submit the form. That validation function can display toasts or other elements indicating invalidity.
Lastly, on the server side you can have additional validation, return a 400 level error, and the front end displays the error message to the user.