Form Validation with Tailwind CSS (without Javascript)

Last updated on June 3, 2022 Pennywise Loading... Post a comment

In Tailwind CSS, we can validate a form without writing any Javascript code. The main point here is to add the peer utility class to the input field we want to validate and then use the peer-invalid modifier to show an error message when the entered value is invalid. Words might be confusing and hard to understand. The complete example below will give a better understanding.

Example Preview

This example creates a minimal contact form. The requirements are:

  • The name must not be empty
  • The email address must be a valid email address
  • The message must be at least one character

When a field does not satisfy the requirements, a corresponding error message will appear right below it. Here’s the demo:

Note: If you’re using Safari, this demo video might not work nicely or not start at all. Please use Chrome, Edge, Firefox, or another web browser instead.

The Code

<body class="w-screen h-screen bg-purple-700 flex justify-center items-center">
    <form class="p-10 bg-white rounded-lg drop-shadow-lg space-y-4" action="">
        <h1 class="text-xl font-light">Contact KindaCode.com</h1>

        <!-- Name -->
        <div class="flex flex-col">
            <label for="name">Name</label>
            <input type="text" name="name" id="name" required class="peer border border-slate-400">

            <p class="invisible peer-invalid:visible text-red-700 font-light">
                Please enter your name
            </p>
        </div>

        <!-- Email -->
        <div class="flex flex-col">
            <label for="email">Email</label>
            <input type="email" name="email" id="email" required class="peer border border-slate-400">
            <p class="invisible peer-invalid:visible text-red-700 font-light">
                Please enter a valid email address
            </p>
        </div>

        <!-- Message -->
        <div class="flex flex-col">
            <label for="message">Message</label>
            <textarea name="message" id="message" cols="30" rows="3" required
                class="peer border border-slate-400"></textarea>
            <p class="invisible peer-invalid:visible text-red-700 font-light">
                This field cannot be empty
            </p>
        </div>
        <button type="submit" class="px-5 py-1 bg-amber-500">Send</button>
    </form>
</body>

That’s if. Further reading:

You can also check out our CSS category page for the latest tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

You May Also Like