Home > Web Front-end > CSS Tutorial > HTML5 Forms: Input Types (Part 1) - SitePoint

HTML5 Forms: Input Types (Part 1) - SitePoint

Christopher Nolan
Release: 2025-02-18 08:28:10
Original
455 people have browsed it

Detailed explanation and best practices for HTML5 form input types

HTML5 Forms: Input Types (Part 1) - SitePoint

Core points

  • HTML5 forms introduce new input types, such as email, search, date, time, number, range, color, etc. These types provide user interface elements and native data verification functions that are more consistent with data types. Even in older browsers, these new input types work properly, except that they will appear as standard text fields by default.
  • search input type (type="search") provides a search field to provide users with intuitive search site prompts. It usually comes with a built-in clear button and can be styled to match the search box of the browser or operating system.
  • email input type (type="email") is used to specify one or more email addresses. It supports the Boolean multiple attribute for multiple comma-separated email addresses. Touchpad devices usually display keyboards optimized for email input when this field gets focus, and some browsers also provide error messages for invalid email input.
  • url input type (type="url") is used to specify a network address, similar to the email input type, which displays as a normal text field, but provides a keyboard optimized for network address input on the touch screen. Modern browsers use this input type to verify the general protocol format of the URL.

(The following is excerpted from the book "HTML5 & CSS3 for the Real World, 2nd Edition" co-authored by Alexis Goldstein, Louis Lazaris and Estelle Weyl. The book is available in stores around the world, and you can also find it here. Purchase the e-book version. )

You may already be familiar with the input attributes of the type element. This property determines which type of form input will be presented to the user. If this property is omitted—or for new input types and older browsers, if the browser does not understand the type—it remains valid; the input will default to type="text". This is what makes HTML5 forms still work today, even if you are still supporting older browsers. If you use a new input type, such as email or search, the older browser will only display standard text fields to the user.

Our registration form currently uses four of the ten input types you are familiar with: checkbox, text, password, and submit. Here is a list of all types available before HTML5:

  • button
  • checkbox
  • file
  • hidden
  • image
  • password
  • radio
  • reset
  • submit
  • text

HTML5 specification provides us with nine new input types that provide UI elements and native data verification capabilities that are more data-type-compliant:

  • search
  • email
  • url
  • tel
  • date
  • time
  • number
  • range
  • color

HTML5.1 and WHATWG HTML Living Standard contain four additional date input types, three of which are well supported in modern browsers:

  • datetime-local
  • month
  • week
  • datetime (no browser supports it)

Let's learn more about each new type and how to use them.

Search (Search)

search input type (type="search") provides a search field - a single-line text input control for entering one or more search terms. Specification points out:

The difference between text state and search state is mainly in style: On platforms where the search field is different from the normal text field, the search state may cause the appearance to be consistent with the platform's search field, rather than like the normal text field .

Many browsers style search inputs in a consistent manner as the search box of the browser or operating system. Currently, Chrome, Safari, Opera, and IE have added the function of clearing input by clicking the mouse to provide the × icon after entering text, as shown in Figure 4.5. The date/time input type can also be cleared in Chrome and Opera. IE11 now also includes a × icon to clear most input types, including input with type text.

HTML5 Forms: Input Types (Part 1) - SitePoint

Figure 4.5. The style of the search input type is similar to the search field of the operating system

On Apple devices, the search fields in Chrome, Safari, and Opera have rounded corners by default, matching the device's search field appearance. On a touchpad with a dynamic keyboard, the “go” button will appear as the search icon or the word “search”, depending on the device. If you include non-standard results properties, Chrome and Opera will display the magnifying glass/find icon in the form field.

While you can still use type="text" to create search fields, the new search type can intuitively prompt users where to search for sites and provide an interface for users to be accustomed to. HTML5 HeraldThere is no search field, but here is an example of how to use it:

<form id="search" method="get">
  <label for="s">Search:</label>
  <input type="search" id="s" name="s"/>
  <input type="submit" value="Search"/>
</form>
Copy after login
Copy after login

Since search, like all new input types, appears as a regular text box in unsupported browsers, there is no reason not to use it when appropriate.

Email Addresses (Email Addresses)

email type (type="email") is used to specify one or more email addresses. It supports Boolean multiple attributes, allowing multiple comma-separated (optional spaces) email addresses. Let's change the form to use type="email" for the registrant's email address:

<form id="search" method="get">
  <label for="s">Search:</label>
  <input type="search" id="s" name="s"/>
  <input type="submit" value="Search"/>
</form>
Copy after login
Copy after login

If you change the input type from text to email, as we do here, you will notice that there is no noticeable change in the user interface; the input still looks like a normal text field. However, there are differences behind the scenes.

If you are using a touchpad device, this change becomes obvious. When you focus on the email field, most touchpad devices, such as iPads or Android phones running Chromium, display keyboards optimized for email input, including @ symbols, periods, and space buttons, but not commas, As shown in Figure 4.6.

HTML5 Forms: Input Types (Part 1) - SitePoint

Figure 4.6. Email input type provides a custom keyboard on iOS device

Firefox, Chrome, Opera, and Internet Explorer 10 also provides error messages for invalid email input: If you try to submit a form that does not recognize as one or more email addresses, the browser will tell you what's wrong . The default error message is shown in Figure 4.7.

HTML5 Forms: Input Types (Part 1) - SitePoint

Figure 4.7. Error message for incorrectly formatted email addresses on Opera (left) and Firefox (right)

Note: Custom verification messages do not like the default error messages provided by the browser? Use .setCustomValidity(errorMsg) to set your own message. setCustomValidity only accepts one parameter, the error message you want to provide. If you set up a custom validation message, once the value becomes a valid value, you must set the validation message to an empty string (false value) to enable form submission:

<label for="email">My email address is:</label>
<input type="email" id="email" name="email"/>
Copy after login

Unfortunately, while you can change the content of the message, at least for the time being you are still limited by its appearance.

URL

url input (type="url") is used to specify the network address. Much like email, it will appear as a normal text field. On many touch screens, the displayed on-screen keyboard will be optimized for network address input, with forward slashes (/) and ".com" shortcuts. Let's update our registration form to use the url input type:

function setErrorMessages(formControl) {
  var validityState_object = formControl.validity;
  if (validityState_object.valueMissing) {
      formControl.setCustomValidity('Please set an age (required)');  
  } else if (validityState_object.rangeUnderflow) {
      formControl.setCustomValidity('You\'re too young');
  } else if (validityState_object.rangeOverflow) {
      formControl.setCustomValidity('You\'re too old');
  } else if (validityState_object.stepMismatch) {
      formControl.setCustomValidity('Counting half birthdays?');
  } else {
      //如果有效,必须设置虚假值,否则将始终出错
      formControl.setCustomValidity('');
  }
}
Copy after login

Verification of URL

All modern browsers starting with Internet Explorer 10 support url input types, and if the value does not start with a protocol, the input will be reported to be invalid. Only validate the general protocol format of the URL, so for example, q://example.xyz will be considered valid, even if q:// is not a real protocol, .xyz is not a real top-level domain. If you want the entered value to fit a more specific format, provide information in the tag (or placeholder) to inform the user and use the pattern attribute to ensure its correctness, as mentioned earlier.

Telephone Numbers (Telephone Numbers)

For phone numbers, use tel input type (type="tel"). Unlike url and email types, tel types do not enforce specific syntax or pattern. Letters and numbers—actually, any character except line breaks or carriage return—are valid. This has a good reason: around the world, every country has valid phone numbers of various lengths and punctuation, so it is impossible to specify a single format as a standard. For example, in the United States, 1(415)555-1212 is as easy to understand as 415.555.1212, but companies may also use letters in phone numbers, such as (800)CALL-NOW. You can encourage specific formatting by including placeholders with correct syntax or comments after input, along with examples. Additionally, you can specify the format using the pattern attribute. Include a pattern in the title attribute to provide tooltips and improve the user experience of native verification error messages. You can also use the setCustomValidity method to provide more informative client verification. When using the tel input type, the dynamic touchpad usually displays the phone keyboard, including the asterisk and pound keys. You can use tel for other purposes than phone numbers. For example, it may be the best keyboard for social security number form input.

FAQs for HTML5 Form Input Types (FAQs)

What are the different types of input types of HTML5 forms?

HTML5 introduces various new form input types. These include "color", "date", "datetime-local", "email", "month", "number", "range", "search", "tel", "time", "url" and "week ”. Each input type has its specific purpose and can greatly enhance the user experience of the website by providing more appropriate and user-friendly input fields.

How does the "date" input type in HTML5 work?

The "date" input type in HTML5 creates an input field that allows the user to enter a date. The date format is formatted according to the user's browser locale and a date selector is usually provided for user convenience. However, support for this input type varies from browser to browser.

What happens when viewing HTML5 form input types in older browsers?

If you view the HTML5 form input type in an older browser that does not support it, the browser will default to the standard "text" input field. This means that the user can still enter information, but specific features of the HTML5 input type (such as the date selector for the "date" input type) will not be available.

How to verify user input in HTML5 form?

HTML5 provides multiple attributes for input verification, including "required", "pattern", and "min"/"max" of numeric input types. These properties can be used to ensure that user input meets specific criteria before the form is submitted.

What is the "range" input type in HTML5?

The "range" input type in HTML5 creates a slider that allows the user to select values ​​within a specific range. You can specify the range using the "min" and "max" properties and specify the default value using the "value" properties.

How does the "email" input type in HTML5 enhance the user experience?

The "email" input type in HTML5 provides a convenient way for users to enter their email address. It includes built-in verification to check if the entered text is in the email address format. Some browsers may also provide autocomplete for this input type.

What is the purpose of the "search" input type in HTML5?

The "search" input type in HTML5 is designed for search fields. This input type can provide search-specific features, such as clearing the search box with one click, or showing the most recent search results to the user.

How to use the "number" input type in HTML5?

The "number" input type in HTML5 allows the user to enter digital input. You can use the min and max properties to specify acceptable range of numbers and use the 'step' property to specify step values.

What is the "tel" input type in HTML5 for?

The "tel" input type in HTML5 is used for the input field that should contain the phone number. However, it does not verify the input, so you should use JavaScript or similar techniques for verification.

How does the "url" input type in HTML5 work?

The "url" input type in HTML5 is used for input fields that should contain URLs. It includes built-in verification to check if the entered text is in URL format. Some browsers may also provide autocomplete for this input type.

The above is the detailed content of HTML5 Forms: Input Types (Part 1) - SitePoint. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template