0Pricing
Tailwind CSS Academy · 课时

验证与错误状态

使用条件颜色 class 设置表单字段的成功和错误状态,涵盖边框、环形和辅助文本。

验证与错误状态 是 CoddyKit 上的免费 Tailwind CSS Academy 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Tailwind CSS Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Tailwind CSS Academy 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

Why Visible Validation Matters

Poor form validation feedback is one of the top causes of form abandonment. Users who fill in a field incorrectly need to know immediately which field is wrong and why. Vague error messages like Form contains errors are not helpful.

With Tailwind, you communicate validation state through three visual channels: the input border color, a colored ring on focus, and an error message beneath the field with an icon. This multi-channel approach helps all users, including those with color vision deficiencies.

Error State Input Styling

An error input switches its border to red: replace border-gray-300 with border-red-500. On focus, show a red ring instead of the usual blue: focus:ring-red-500.

The combination of a red border in the default state and a red ring on focus ensures the error is visible both when the field is active and when the user has moved on to another field. Add a subtle red background tint bg-red-50 for extra emphasis on critical errors.

<!-- Error state input -->
<input
  type="email"
  value="not-an-email"
  aria-invalid="true"
  aria-describedby="email-error"
  class="w-full px-3 py-2 text-sm text-gray-900 bg-red-50
         border border-red-500 rounded-lg
         focus:outline-none focus:ring-2 focus:ring-red-500 focus:border-transparent"
/>

Error Message Below the Field

An error message appears below the input to explain what went wrong. Use flex items-center gap-1 mt-1 text-xs text-red-600 on the message container. Add an icon for extra clarity — a small exclamation circle in red reinforces the error state visually.

Connect the error message to the input with aria-describedby on the input and a matching id on the message paragraph. This allows screen readers to announce the error automatically when the field receives focus.

<div class="flex flex-col gap-1">
  <label for="email" class="text-sm font-medium text-gray-700">Email address</label>
  <input
    id="email"
    type="email"
    value="bad-email"
    aria-invalid="true"
    aria-describedby="email-err"
    class="w-full px-3 py-2 text-sm border border-red-500 bg-red-50 rounded-lg
           focus:outline-none focus:ring-2 focus:ring-red-500"
  />
  <p id="email-err" role="alert" class="flex items-center gap-1 mt-1 text-xs text-red-600">
    <svg class="w-3.5 h-3.5" fill="currentColor" viewBox="0 0 20 20">
      <path fill-rule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7 4a1 1 0 11-2 0 1 1 0 012 0zm-1-9a1 1 0 00-1 1v4a1 1 0 102 0V6a1 1 0 00-1-1z" clip-rule="evenodd"/>
    </svg>
    Please enter a valid email address.
  </p>
</div>

Success State Input Styling

When a field passes validation, show a success state with a green border and a checkmark icon below the field. Replace border-red-500 with border-green-500 and use focus:ring-green-500 for the focus ring.

A success message uses flex items-center gap-1 mt-1 text-xs text-green-600 with a checkmark icon. Success states are particularly valuable for real-time validation (such as username availability checks) where user confidence benefits from immediate positive feedback.

<div class="flex flex-col gap-1">
  <label for="username" class="text-sm font-medium text-gray-700">Username</label>
  <input
    id="username"
    type="text"
    value="awesome_dev"
    class="w-full px-3 py-2 text-sm border border-green-500 bg-green-50 rounded-lg
           focus:outline-none focus:ring-2 focus:ring-green-500"
  />
  <p class="flex items-center gap-1 mt-1 text-xs text-green-600">
    <svg class="w-3.5 h-3.5" fill="currentColor" viewBox="0 0 20 20">
      <path fill-rule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clip-rule="evenodd"/>
    </svg>
    Username is available!
  </p>
</div>

Conditional Classes With JavaScript

In real applications, error and success states are applied conditionally based on validation results. In vanilla JavaScript, this means toggling classes on the input and showing/hiding the error message element.

The pattern is to apply a default neutral class set, an error class set, and a success class set — then add exactly one of these to the input when needed. Removing all state classes before adding the new state prevents class conflicts.

<script>
  function validateEmail(input) {
    const errorEl = document.getElementById('email-error');
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

    // Remove previous states
    input.classList.remove(
      'border-gray-300', 'border-red-500', 'border-green-500',
      'focus:ring-blue-500', 'focus:ring-red-500', 'focus:ring-green-500'
    );

    if (!emailRegex.test(input.value)) {
      input.classList.add('border-red-500', 'focus:ring-red-500');
      errorEl.classList.remove('hidden');
    } else {
      input.classList.add('border-green-500', 'focus:ring-green-500');
      errorEl.classList.add('hidden');
    }
  }
</script>
<input type="email" onblur="validateEmail(this)"
       class="w-full px-3 py-2 text-sm border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" />

Form-Level Error Summary

For complex forms, display a form-level error summary at the top when the user attempts to submit with multiple invalid fields. This saves users from having to scroll through the entire form to discover all errors.

Style the summary as a red alert box: border border-red-200 bg-red-50 rounded-lg p-4 with an error icon and an unordered list of error messages. Focus this element on display so keyboard and screen reader users immediately hear the summary.

<div role="alert" class="border border-red-200 bg-red-50 rounded-lg p-4 mb-6">
  <div class="flex items-center gap-2 mb-2">
    <svg class="w-5 h-5 text-red-500" fill="currentColor" viewBox="0 0 20 20">
      <path fill-rule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7 4a1 1 0 11-2 0 1 1 0 012 0zm-1-9a1 1 0 00-1 1v4a1 1 0 102 0V6a1 1 0 00-1-1z" clip-rule="evenodd"/>
    </svg>
    <p class="text-sm font-semibold text-red-700">Please fix the following errors:</p>
  </div>
  <ul class="ml-5 list-disc space-y-1">
    <li class="text-sm text-red-600">Email address is required.</li>
    <li class="text-sm text-red-600">Password must be at least 8 characters.</li>
  </ul>
</div>

Warning State for Non-Blocking Issues

A warning state indicates a potentially problematic but non-blocking condition — for example, a password that meets minimum requirements but is weak, or a username that is available but similar to an existing one.

Use amber/yellow for warnings: border-yellow-400 on the input and text-yellow-700 on the message with a warning icon. The warning should not block form submission — it is informational, not a blocking error.

<div class="flex flex-col gap-1">
  <label for="pw-warn" class="text-sm font-medium text-gray-700">Password</label>
  <input
    id="pw-warn"
    type="password"
    value="password123"
    class="w-full px-3 py-2 text-sm border border-yellow-400 rounded-lg
           focus:outline-none focus:ring-2 focus:ring-yellow-400"
  />
  <p class="flex items-center gap-1 mt-1 text-xs text-yellow-700">
    <svg class="w-3.5 h-3.5" fill="currentColor" viewBox="0 0 20 20">
      <path fill-rule="evenodd" d="M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z" clip-rule="evenodd"/>
    </svg>
    Weak password. Consider adding symbols or uppercase letters.
  </p>
</div>

Password Strength Indicator

A password strength bar is a visual component that updates in real time as the user types. Implement it as a narrow bar below the input split into segments that fill with color as the password grows stronger.

Use a flex gap-1 container with multiple h-1 rounded-full segments. Color them conditionally: gray for empty, red for weak, yellow for medium, and green for strong. This is a practical example of conditional class application in Tailwind.

<!-- 4-segment strength bar -->
<div class="flex gap-1 mt-2">
  <!-- Segment 1: always filled if any input -->
  <div class="flex-1 h-1.5 rounded-full bg-red-500"></div>
  <!-- Segment 2: filled if medium+ -->
  <div class="flex-1 h-1.5 rounded-full bg-yellow-400"></div>
  <!-- Segment 3: filled if strong -->
  <div class="flex-1 h-1.5 rounded-full bg-gray-200"></div>
  <!-- Segment 4: filled if very strong -->
  <div class="flex-1 h-1.5 rounded-full bg-gray-200"></div>
</div>
<p class="mt-1 text-xs text-yellow-600 font-medium">Medium strength</p>

Shake Animation on Invalid Submit

Adding a brief shake animation to an invalid form on submit provides immediate kinetic feedback. Define a custom shake keyframe in tailwind.config.js and apply it with animate-shake.

The shake animation consists of rapid horizontal translations: 0% → -10px → 10px → -5px → 5px → 0. Trigger it by adding the class on submission and removing it after the animation completes using the animationend event listener.

// tailwind.config.js
module.exports = {
  theme: {
    extend: {
      keyframes: {
        shake: {
          '0%, 100%': { transform: 'translateX(0)' },
          '10%, 30%, 50%, 70%, 90%': { transform: 'translateX(-6px)' },
          '20%, 40%, 60%, 80%': { transform: 'translateX(6px)' },
        },
      },
      animation: {
        shake: 'shake 0.4s ease-in-out',
      },
    },
  },
};

// Usage:
// form.classList.add('animate-shake');
// form.addEventListener('animationend', () => form.classList.remove('animate-shake'), { once: true });

Real-Time Validation Timing

Triggering validation at the right moment is as important as the visual style. Validating on every keystroke (oninput) is annoying for users who have not finished typing. Validating only on submit means users do not see feedback until they are done with the whole form.

The best practice is validate on blur (onblur): show errors when the user leaves a field. Once the error is showing, switch to oninput for that field so the error clears as soon as it is fixed, giving immediate positive feedback.

<script>
  let hasError = false;

  const input = document.getElementById('live-email');
  const errorEl = document.getElementById('live-error');

  // Validate on blur (leaving the field)
  input.addEventListener('blur', () => {
    if (!input.value.includes('@')) {
      hasError = true;
      input.classList.add('border-red-500');
      errorEl.classList.remove('hidden');
    }
  });

  // Once error shown, clear in real time
  input.addEventListener('input', () => {
    if (hasError && input.value.includes('@')) {
      hasError = false;
      input.classList.remove('border-red-500');
      input.classList.add('border-green-500');
      errorEl.classList.add('hidden');
    }
  });
</script>

Accessible Error Announcements

Screen readers do not automatically announce dynamically injected error messages unless the element has role='alert' or aria-live='polite'. Adding role='alert' to the error message paragraph causes the screen reader to interrupt and read the message as soon as it appears in the DOM.

Use aria-invalid='true' on invalid inputs and aria-describedby pointing to the error message ID so screen readers announce the context when the field receives focus.

<div class="flex flex-col gap-1">
  <label for="acc-email" class="text-sm font-medium text-gray-700">Email</label>
  <input
    id="acc-email"
    type="email"
    aria-invalid="true"
    aria-describedby="acc-email-error"
    class="w-full px-3 py-2 text-sm border border-red-500 rounded-lg
           focus:outline-none focus:ring-2 focus:ring-red-500"
  />
  <!-- role=alert makes screen readers announce this when it appears -->
  <p id="acc-email-error" role="alert" class="flex items-center gap-1 mt-1 text-xs text-red-600">
    <svg class="w-3.5 h-3.5" fill="currentColor" viewBox="0 0 20 20">
      <path fill-rule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7 4a1 1 0 11-2 0 1 1 0 012 0zm-1-9a1 1 0 00-1 1v4a1 1 0 102 0V6a1 1 0 00-1-1z" clip-rule="evenodd"/>
    </svg>
    Please enter a valid email address.
  </p>
</div>

Quick Check

Test your understanding of Tailwind CSS Mastery concepts from this lesson.

Lesson Recap

In this lesson you learned: error state inputs use border-red-500 with focus:ring-red-500 and a bg-red-50 tint; error messages appear below the field with text-xs text-red-600 and a warning icon; and accessibility requires aria-invalid, aria-describedby, and role='alert' so screen readers announce errors automatically. Next up we build modal dialog components.

常见问题解答

「验证与错误状态」课时是免费的吗?

是的 — 「验证与错误状态」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Tailwind CSS Academy 课程的其余内容,请升级到 CoddyKit PRO。 Tailwind CSS Academy 课程共包含 4 节课。

「验证与错误状态」这节课中我会学到什么?

使用条件颜色 class 设置表单字段的成功和错误状态,涵盖边框、环形和辅助文本。 你通过在浏览器中直接运行的动手代码来练习 Tailwind CSS Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Tailwind CSS Academy 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Tailwind CSS Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。

「验证与错误状态」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Tailwind CSS Academy 课中编写并运行代码吗?

能。每节 Tailwind CSS Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 设置文本输入框与文本区域样式
  2. 选择菜单与复选框
  3. 表单布局模式
  4. 验证与错误状态
← 返回 Tailwind CSS Academy