When we refresh the page or first come to the page, the error messages are already visible. Showing the error messages right away isn’t good for usability.
So: JavaScript to the rescue. With a little JS we can hide the error messages by default, then when the user submits the form we can display the error messages at that point.
Don’t worry though, the JS is pre-written and ready to run.
First we need to add a new attribute to the <form>
tag: the novalidate
attribute. It tells the browser not to run it’s default validation and allows our JavaScript to control the validation instead.
⋮
</head>
<body>
<form class="max-length island" method="post" action="#" novalidate>
⋮
Then down at the bottom of the code we add the actual <script>
tag to the JS file.
⋮
<button class="btn" type="submit">Send</button>
</div>
</form>
<script src="https://thomasjbradley.github.io/form-validation-helper/index.js"></script>
</body>
</html>
Here’s the JavaScript URL for quick copying-and-pasting:
https://thomasjbradley.github.io/form-validation-helper/index.js