阿里云主机折上折
  • 微信号
Current Site:Index > The new input types added in HTML5 ('email', 'url', 'number', etc.)

The new input types added in HTML5 ('email', 'url', 'number', etc.)

Author:Chuan Chen 阅读数:32370人阅读 分类: HTML

HTML5 introduced various new input types for forms, which not only enhance user experience but also simplify validation for developers. From email addresses to numeric ranges and date pickers, these new types make form handling more efficient and precise.

Email Type

The email type is specifically designed for entering email addresses. Browsers automatically validate whether the input follows the basic structure of an email (e.g., containing an @ symbol). If the user's input doesn't meet the requirements, an error prompt is displayed upon form submission.

<input type="email" id="userEmail" name="userEmail" required>

Features:

  • Mobile devices automatically display a keyboard layout suitable for email input (e.g., including @ and . symbols).
  • Supports the multiple attribute, allowing multiple email addresses to be entered (separated by commas):
    <input type="email" id="emails" name="emails" multiple>
    

Validation Example:

document.querySelector('form').addEventListener('submit', (e) => {
  const emailInput = document.getElementById('userEmail');
  if (!emailInput.validity.valid) {
    alert('Please enter a valid email address');
    e.preventDefault();
  }
});

URL Type

The url type is used for entering URL addresses. Browsers validate whether the input includes a protocol (e.g., http:// or https://).

<input type="url" id="website" name="website" placeholder="https://example.com">

Note:

  • Some browsers may not enforce the protocol prefix, but for compatibility, it's recommended to include a hint in the input field.
  • Invalid inputs can be highlighted using the CSS :invalid pseudo-class:
    input:invalid { border: 2px solid red; }
    

Number Type

The number type restricts users to entering only numbers. Additional attributes can further control the input range:

<input type="number" id="quantity" name="quantity" min="1" max="100" step="5">

Attribute Explanation:

  • min/max: Minimum/maximum allowed values
  • step: Increment/decrement step (e.g., step="0.1" allows decimal input)
  • Mobile devices display a numeric keyboard

Practical Application:

<label for="temperature">Temperature Setting (°C):</label>
<input type="number" id="temperature" name="temperature" min="-20" max="50" value="25">

Range Type

The range type generates a slider control, suitable for scenarios where precise values aren't necessary:

<input type="range" id="volume" name="volume" min="0" max="11" value="7">

Enhanced Interaction: The current value can be displayed in real-time using JavaScript:

const range = document.getElementById('volume');
const output = document.createElement('span');
output.textContent = range.value;
range.parentNode.insertBefore(output, range.nextSibling);
range.addEventListener('input', () => {
  output.textContent = range.value;
});

Date/Time-Related Types

HTML5 provides a series of date and time pickers:

<!-- Date selection -->
<input type="date" id="birthday" name="birthday">

<!-- Time selection -->
<input type="time" id="meetingTime" name="meetingTime" min="09:00" max="18:00">

<!-- Week selection -->
<input type="week" id="vacationWeek" name="vacationWeek">

<!-- Month selection -->
<input type="month" id="expiry" name="expiry">

Timezone Handling: Date and time values are always submitted in ISO format (e.g., 2024-03-15T13:45:00). Note the need for timezone conversion on the server side.

Color Type

The color type provides a color picker:

<input type="color" id="bgColor" name="bgColor" value="#ff0000">

Dynamic Application Example:

document.getElementById('bgColor').addEventListener('input', (e) => {
  document.body.style.backgroundColor = e.target.value;
});

Search Type

The search type is optimized for search boxes, with some browsers adding a clear button:

<input type="search" id="siteSearch" name="q" results="5">

Note:

  • The results attribute (deprecated) was originally used to display the number of historical records
  • The clear button can be styled using the webkit-search-cancel-button pseudo-element

Tel Type

The tel type is used for phone number input, with mobile devices switching to a numeric keyboard:

<input type="tel" id="phone" name="phone" pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}">

Advanced Usage: Combined with international phone number libraries (e.g., libphonenumber) for more robust validation:

// Example: Using libphonenumber for validation
const phoneNumber = window.libphonenumber.parsePhoneNumberFromString(
  document.getElementById('phone').value,
  'US'
);
if (!phoneNumber || !phoneNumber.isValid()) {
  alert('Invalid phone number');
}

Other Special Types

Datalist Element

While not an input type, it's often used with text inputs for autocomplete functionality:

<input list="browsers" name="browser">
<datalist id="browsers">
  <option value="Chrome">
  <option value="Firefox">
  <option value="Safari">
</datalist>

Input Mode (inputmode)

Enhances mobile keyboard display:

<input type="text" inputmode="numeric" pattern="[0-9]*">

Browser Compatibility Practices

While modern browsers generally support these types, fallback solutions are needed:

<input type="number" id="age" name="age">
<script>
  if (!document.createElement('input').type === 'number') {
    // Fallback handling
    document.getElementById('age').type = 'text';
    document.getElementById('age').pattern = '[0-9]*';
  }
</script>

Validation API Integration

All new input types support the Constraint Validation API:

const input = document.getElementById('email');
if (input.validity.typeMismatch) {
  console.log('A valid email address is required');
}
if (input.validity.rangeOverflow) {
  console.log('Value exceeds the maximum allowed');
}

Mobile Optimization Tips

Best practices for touch devices:

  • Add min/max limits to date types to restrict selectable ranges
  • Use step="any" to allow arbitrary decimal input:
    <input type="number" step="any" id="price">
    
  • Avoid using the range type for precise control on mobile devices

本站部分内容来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn

Front End Chuan

Front End Chuan, Chen Chuan's Code Teahouse 🍵, specializing in exorcising all kinds of stubborn bugs 💻. Daily serving baldness-warning-level development insights 🛠️, with a bonus of one-liners that'll make you laugh for ten years 🐟. Occasionally drops pixel-perfect romance brewed in a coffee cup ☕.