DEV Community


Validating a form with IodineJS

mattkingshott profile image Matt Kingshott 👨🏻‍💻 Originally published at on ・2 min read

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.

The HTML Page

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.

The JavaScript Code

Now let’s take a look at the register JavaScript function that is triggered by the browser when the button is clicked:

Let’s break down what is happening here:

  1. First, we have a top level flag that indicates whether the form is valid or not. By default, we will assume it is not.
  2. 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.
  3. Within the register function, we disable the browser’s native behaviour when clicking a button in a form (which is to immediately submit it).
  4. We then set the valid flag to true so the form can be submitted.
  5. We iterate through each field in the rules object, find its corresponding input on the page and retrieve its value.
  6. Next, the input’s validation error is hidden. That way, we don’t need to do anything to it if the validation passes.
  7. We then have Iodine validate the field. If this fails, we set the valid flag to false, fetch the error message and display it.
  8. Finally once all the fields have been validated, we check the valid flag. If it is still true, we then submit the form.

Wrapping up

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!

Discussion (0)

Forem Open with the Forem app