A few days ago, I released IodineJS, a micro client-side validation library built using the principles of simplicity, ease-of-use and speed. You can learn more about how it works and why I built it in the release article. Today, we’re going to look at a simple example of validating a form with Iodine.
Let’s begin with the HTML. We have a simple registration form where we accept a user name and an email address. We also have a submit button and hidden spans that will contain any failed validation messages.
In the gist, you’ll see numerous references to utility css classes. These are part of the amazing Tailwind CSS library that I use in all my apps. They’re present to make the form look nice, but they are not required to use Iodine.
Let’s break down what is happening here:
- First, we have a top level flag that indicates whether the form is valid or not. By default, we will assume it is not.
- Next, we have a simple object containing each of the field names and the validation rules that we want to enforce for them. You can learn more about this, and the rules being used, by examining the repo’s readme.
- Within the register function, we disable the browser’s native behaviour when clicking a button in a form (which is to immediately submit it).
- We then set the valid flag to true so the form can be submitted.
- We iterate through each field in the rules object, find its corresponding input on the page and retrieve its value.
- Next, the input’s validation error is hidden. That way, we don’t need to do anything to it if the validation passes.
- We then have Iodine validate the field. If this fails, we set the valid flag to false, fetch the error message and display it.
- Finally once all the fields have been validated, we check the valid flag. If it is still true, we then submit the form.
I hope this simple example has shown you just how easy it is to integrate Iodine into your applications / pages. Indeed, within the example itself, Iodine only accounts for around 5 lines of code!
I encourage you to check out the readme for more details and examples.
If you’d like to keep up to date with news about Iodine and other projects, then please follow me on Twitter. Thanks for reading and have a great day!