Skip to Content
UX Patterns for Devs GPT is now available! Read more →

Text Field

Example of text-field pattern

Overview

A Text Field is a fundamental form input component that allows users to enter and edit text-based data. It is commonly used in forms, search fields, authentication fields, and messaging interfaces.

Text fields can accept single-line or multi-line input and may include additional features like placeholders, character counters, validation messages, and formatting assistance.

Build Effort

🟢Low

Requires basic HTML input handling, validation, keyboard navigation, and optional accessibility attributes.

Use Cases

When to use:

Use a text field when you need users to input freeform text, such as:

  • Login and authentication fields – Username, password, email.
  • Search fields – Query inputs in search bars.
  • Forms and surveys – Collecting names, addresses, or custom responses.
  • Messaging interfaces – Chat applications and comment sections.
  • Data entry fields – User-generated content like tags, descriptions, or reviews.

When not to use:

  • For pre-defined options – Use dropdowns, radio, or checkboxes instead.
  • For structured data inputs – Use specialized inputs like date pickers or currency fields.
  • For short selections – Use auto-complete inputs instead of requiring full text input.
  • When voice input or selections are better – Consider alternatives for accessibility.

Benefits

  • Flexible – Allows users to enter freeform responses.
  • Widely recognized – Standardized interaction that users expect.
  • Supports real-time validation – Instant feedback for user input.
  • Can be enhanced – Custom validation, auto-formatting, and assistance.

Drawbacks

  • User errors – Freeform text increases the risk of typos and incorrect formatting.
  • Lack of guidance – May require placeholders, labels, or tooltips to improve usability.
  • Accessibility concerns – Must be properly labeled and include validation feedback for screen readers.

Anatomy

Component Structure

  1. Container (div or fieldset)

    • Wraps the entire text field component.
    • Ensures proper spacing and alignment.
    • May include additional styling or group related inputs.
  2. Label (label)

    • Describes the purpose of the input field.
    • Should be visually positioned above the input.
    • Must be associated with the input using the for attribute.
  3. Input Field (input[type="text"])

    • The interactive area where users enter text.
    • Supports attributes such as autocomplete, maxlength, and required.
    • Should have proper focus styles for accessibility.
  4. Placeholder (Optional)

    • Provides a hint before users type.
    • Disappears when input is focused.
    • Should not replace a label for accessibility.
  5. Helper Text (p or span, optional)

    • Provides additional guidance or formatting instructions.
    • Typically placed below the input field.
    • Should be persistent and not disappear on focus.
  6. Validation/Error Message (p or span, optional)

    • Displays a clear, specific message when input is invalid.
    • Should be associated with the input using aria-describedby.
    • Appears below the input, replacing helper text if necessary.
  7. Character Counter (p or span, optional)

    • Displays remaining or used character count (e.g., “20/100 characters”).
    • Helps users stay within input length limits.
    • Should update dynamically as the user types.
  8. Prefix (span, optional)

    • Static text before the input (e.g., $ for currency, @ for usernames).
    • Should be visually distinguishable from user input.
  9. Suffix (span, optional)

    • Static text after the input (e.g., .com for domain fields).
    • Helps users understand expected input formats.

Summary of Components

ComponentRequired?Purpose
Label✅ YesDescribes the input field’s purpose.
Input Field✅ YesThe main interactive element for user input.
Placeholder❌ NoProvides a hint but disappears on input.
Helper Text❌ NoOffers guidance or additional instructions.
Validation/Error Message❌ NoProvides feedback when input is invalid.
Character Counter❌ NoTracks remaining/used characters.
Prefix❌ NoDisplays static text before the input.
Suffix❌ NoDisplays static text after the input.

Code Examples

1️⃣ Best Practice: Explicit “Required” Label

Most accessible – clear for all users, including screen readers.

<label for="username"> Username <span>(Required)</span> </label> <input type="text" id="username" name="username" required />

Pros ✅

  • Works for all users, including screen readers and color-blind users.
  • No need for extra ARIA attributes.

Cons ❌

  • Takes slightly more space in the UI.

2️⃣ Alternative: Asterisk (*) with ARIA Explanation

Common practice, but needs aria-describedby for screen reader users.

<label for="username"> Username <span aria-hidden="true">*</span> </label> <input type="text" id="username" name="username" required aria-describedby="required-msg" /> <p id="required-msg" class="sr-only"> Fields marked with an asterisk are required. </p>

Pros ✅

  • Keeps UI cleaner while maintaining accessibility.
  • Screen readers will announce “Fields marked with an asterisk are required.”

Cons ❌

  • Requires additional explanation (aria-describedby).
  • Without the extra message, asterisks alone are not accessible.

3️⃣ Alternative: Required Field with Visually Hidden Text

Keeps UI minimal while ensuring accessibility.

<label for="email"> Email <span class="sr-only">(Required)</span> </label> <input type="email" id="email" name="email" required />

Pros ✅

  • Looks clean visually while still accessible.
  • Screen readers announce it as “Email Required”.

Cons ❌

  • Not visible for sighted users who rely on visual cues.

4️⃣ Alternative: Required Field with an Inline Icon + Tooltip

More user-friendly, provides additional guidance.

<label for="phone"> Phone Number <span aria-hidden="true" class="required-icon" tabindex="0"> *</span> </label> <input type="tel" id="phone" name="phone" required aria-describedby="required-msg" /> <p id="required-msg" class="sr-only"> Fields marked with an asterisk are required. </p>

Pros ✅

  • Visually clear while keeping text minimal.
  • Works well when paired with a tooltip on hover or focus.

Cons ❌

  • Requires CSS for styling (ensuring asterisks are not the only indicator).
  • Users might not see tooltip hints if they don’t hover over the icon.

5️⃣ Alternative: Required Field with required Attribute Only

Not recommended as a standalone solution!

<label for="password"> Password </label> <input type="password" id="password" name="password" required />

Pros ✅

  • Works well for basic validation.
  • Screen readers will announce the field as required.

Cons ❌

  • No visible indicator for sighted users before form submission.
  • Errors only appear after submission, which may confuse users.
  • Some browsers may not enforce required fields consistently.

Best Practices

Content & Usability

Do’s ✅

  • Provide a clear and descriptive label.
  • Use placeholder text sparingly and never as a replacement for a label.
  • Indicate required fields clearly and provide helpful validation feedback.
  • Use real-time validation to prevent errors early.
  • Ensure sufficient touch target size for mobile users.
  • Allow users to copy, paste, and autocomplete when appropriate.
  • Use input masks sparingly—they can improve formatting but may frustrate users if too rigid.
  • Offer formatting hints when users must follow a specific pattern (e.g., phone numbers, dates).
  • Provide default values when applicable to reduce typing effort.

Don’ts ❌

  • Don’t use placeholder text instead of a visible label.
  • Avoid long character limits without a counter.
  • Don’t require unnecessary or sensitive information without justification.
  • Don’t enforce case sensitivity unless absolutely necessary.
  • Avoid disabling copy-paste for passwords or sensitive fields, as this can harm usability.

Accessibility

Do’s ✅

  • Associate the text field with a <label> element for screen readers.
  • Use aria-describedby to connect inputs to error messages or hints.
  • Ensure high contrast between text and background.
  • Provide keyboard navigation and support tabbing.
  • Allow speech-to-text functionality for accessibility.
  • Use aria-invalid="true" when a validation error occurs.
  • Ensure error messages appear next to the field and are read aloud by screen readers.

Don’ts ❌

  • Don’t remove focus outlines—they are essential for keyboard users.
  • Don’t rely solely on color to indicate errors.
  • Avoid using title attributes for tooltips—use visible descriptions.
  • Don’t use placeholder as the only accessible text—it disappears when users start typing.
  • Avoid dynamic placeholder text changes that may confuse assistive technologies.

Visual Design

Do’s ✅

  • Use sufficient padding and line height for readability.
  • Maintain a clear distinction between active, focused, and disabled states.
  • Use icons (optional) for additional context (e.g., search icon in a search field).
  • Ensure error states are visually prominent without being intrusive.
  • Use color contrast that meets WCAG 2.1 AA standards (e.g., 4.5:1 ratio for text).

Don’ts ❌

  • Avoid excessive borders or decorative elements.
  • Don’t make the input field too small, especially on mobile.
  • Avoid low contrast text and background combinations.
  • Don’t rely solely on placeholder text for field instructions.

Layout & Positioning

Do’s ✅

  • Align labels above or beside the text field for clarity.
  • Keep consistent spacing and alignment with other form elements.
  • Ensure sufficient spacing between multiple input fields for easy readability.
  • Place validation messages near the input field to improve error recognition.

Don’ts ❌

  • Don’t position labels too far from the input.
  • Avoid overly narrow text fields that cut off content.
  • Don’t place validation messages too far from the field.
  • Avoid placing multiple fields on the same line on mobile, as this reduces readability.

Input Description Placement: Above or Below the Text Field?

Best Practice: Place Input Descriptions Below the Field

In most cases, input descriptions (helper text, formatting hints, and additional guidance) should be placed below the text field for consistency, readability, and accessibility.

✅ Why?

  • Users scan from top to bottom – The label is read first, then the input, then any additional help.
  • Aligns with error messages – Since validation errors appear below the field, keeping all feedback in one place reduces cognitive load.
  • Screen reader order – Screen readers will naturally announce the description right after the field when placed below.
  • Follows industry standards – Major design systems (Google Material, IBM Carbon, Bootstrap) place helper text below.

📍 When to Place Descriptions Above the Field?

There are some exceptions where placing descriptions above is preferable:

  1. When users must understand something before typing
    • Example: “Enter your National Insurance number in the format QQ123456C”
  2. Password requirements
    • Example: “Password must be at least 8 characters and contain a number.”
  3. When there is no error message below the field
    • Helps avoid excessive space between the input and the next element.

Best Practice: Only Show One at a Time

To avoid overwhelming users:

  • Before an error occurs, display helper text below the input.
  • When an error occurs, replace the helper text with the error message.

Example (Best Practice)

<label for="email">Email</label> <input type="email" id="email" name="email" required aria-describedby="email-info" /> <p id="email-info" class="helper-text"> We'll never share your email with anyone. </p> <!-- Error message replaces helper text when validation fails --> <p id="email-error" class="error-message" style="display: none;"> Please enter a valid email. </p> <script> const emailInput = document.getElementById("email"); const helperText = document.getElementById("email-info"); const errorText = document.getElementById("email-error"); emailInput.addEventListener("input", function () { if (!emailInput.validity.valid) { helperText.style.display = "none"; errorText.style.display = "block"; } else { helperText.style.display = "block"; errorText.style.display = "none"; } }); </script>

Final Recommendation for Input Description Placement

ScenarioWhere to Place Helper Text?Why?
Standard input fields (e.g., email, name, search)BelowEnsures consistency with error messages & better readability.
Inputs with specific formatting (e.g., date, phone number)AboveUsers need to understand format before typing.
Password fields (with complexity rules)AboveUsers need guidance before they type.
Large forms with minimal UIAbove or InlineTo prevent visual clutter.
Error messagesBelowAlways below, ensuring users immediately see what went wrong.

Accessibility

Keyboard Interaction Pattern

Text fields should support standard keyboard navigation and interactions to ensure accessibility and usability.

KeyAction
TabMoves focus to the next interactive element.
Shift + TabMoves focus to the previous interactive element.
Enter (inside a form)Submits the form (unless prevented).
Arrow Left / RightMoves the text cursor within the input.
Arrow Up / DownMoves the cursor within multi-line text fields (textarea).
EscIf inside a search field, clears input (optional behavior).

Testing Guidelines

Functional Testing

Should ✓

  • Verify that users can input, edit, and delete text without issues.
  • Ensure character limits work correctly and display remaining characters if applicable.
  • Validate correct error handling and messaging (e.g., required fields, invalid formats).
  • Confirm keyboard navigation and focus behavior, including tab order.
  • Ensure users can copy, paste, and autofill without restrictions.
  • Test input masks and auto-formatting to confirm they work as expected.
  • Validate that pressing Enter/Return behaves as expected (e.g., form submission or moving to the next field).

Accessibility Testing

Should ✓

  • Ensure text fields have associated labels (<label for="id">) for screen readers.
  • Validate that error messages are announced by screen readers (NVDA, JAWS, VoiceOver, TalkBack).
  • Confirm that keyboard users can navigate and interact effectively using Tab, Shift+Tab, Enter, and Esc.
  • Ensure high contrast between text and background (meets WCAG 2.1 AA contrast ratio).
  • Check that focus indicators are visible when navigating via keyboard.
  • Test with different screen readers to confirm field descriptions and validation messages are correctly read.
  • Verify that speech-to-text functionality works for users relying on voice input.
  • Ensure placeholder text is not the only accessible label, as it disappears when typing.
  • Check for aria-describedby and aria-invalid="true" usage in error handling scenarios.

Performance Testing

Should ✓

  • Ensure text input does not cause delays, freezing, or slow response times.
  • Validate large text input handling (e.g., pasting 1000+ characters into a field).
  • Check browser compatibility across different devices (Chrome, Firefox, Safari, Edge, mobile browsers).
  • Test mobile usability, including touch input, autocorrect behavior, and focus handling.
  • Ensure input fields don’t trigger layout shifts (Cumulative Layout Shift - CLS).
  • Validate lazy loading and deferred scripts do not delay field interactions.
  • Check memory usage when dynamically adding or removing fields.

Security Testing

Should ✓

  • Ensure fields do not store sensitive data in autocomplete history unless necessary (autocomplete="off" for sensitive inputs).
  • Validate against Cross-Site Scripting (XSS) attacks—inputs should sanitize user-entered data.
  • Verify that error messages do not reveal sensitive details (e.g., don’t display “Incorrect email or password” separately).
  • Check that invalid inputs do not break the layout or cause unexpected behavior.

Mobile & Touch Testing

Should ✓

  • Ensure the correct keyboard type appears for each input (e.g., numeric for phone numbers, email keyboard for email fields).
  • Validate touch targets are large enough (at least 44x44px) for usability.
  • Test how input behaves in dark mode and ensure readability.
  • Check if input fields adjust correctly when the virtual keyboard opens (avoiding overlapping content).
  • Ensure users can easily dismiss the keyboard after typing (e.g., tapping outside the input).
  • Verify that autocorrect and autocomplete work properly without interfering with expected input behavior.
  • Confirm that multi-line inputs (textarea) scroll correctly without hiding text on smaller screens.

Error Handling & Validation Testing

Should ✓

  • Ensure validation errors appear next to the relevant input field (not in a separate section).
  • Validate that real-time validation does not trigger prematurely while typing.
  • Confirm that error messages persist until fixed, rather than disappearing too quickly.
  • Ensure errors provide clear guidance (e.g., “Enter a valid email” instead of “Invalid input”).
  • Check if aria-live="polite" announces validation messages dynamically.
  • Test behavior when submitting an empty required field—does it highlight correctly?
  • Verify that server-side validation handles unexpected input gracefully (e.g., very long strings, special characters).
  • Ensure users can recover from errors easily without refreshing the page.

Edge Case Testing

Should ✓

  • Simulate slow network conditions to check if validation messages delay input behavior.
  • Test behavior when copying and pasting large amounts of text into a field.
  • Ensure input remains intact when navigating away and returning to the form.
  • Check how the field handles emoji, special characters, and non-Latin alphabets.
  • Test what happens if a user pastes an entire paragraph into a single-line text field.
  • Verify that auto-suggestions do not interfere with manual input.
  • Test behavior when users press the “back” button on mobile browsers—does the input persist?
  • Ensure users can undo accidental deletions (via Ctrl+Z or long press on mobile).

Frequently Asked Questions

What is a text field in web design?

A text field is an input element that allows users to enter and edit text in forms or interfaces, commonly used for data entry such as names, emails, or search queries.

What are best practices for designing text fields?

Best practices include using clear and visible labels, providing appropriate input types, ensuring sufficient contrast, supporting keyboard navigation, and offering helpful placeholder text when necessary.

How can I make text fields accessible?

Ensure that each text field has a visible label, supports keyboard navigation, provides sufficient color contrast, and includes clear instructions or error messages to assist users with disabilities.

What is the difference between a text field and a text area?

A text field is typically a single-line input for short text, while a text area is a multi-line input designed for longer text entries, such as comments or messages.

Should I use placeholder text as a label?

No, placeholder text should not replace labels. Placeholders can provide examples or hints but should not be used as the primary label, as they disappear when users start typing, potentially causing confusion.

Resources

Libraries

Input - Origin UI

Last updated on