次の方法で共有


Forms

Internet Explorer 10 and Windows apps using JavaScript add new support for HTML5 Forms, including new states of the type attribute (on the input element), new attributes for the input element, and the progress element. This support enables developers to quickly and easily provide user prompting, input validation, and feedback with a minimal amount of script. HTML5 Forms are described in section 4.10 of the World Wide Web Consortium (W3C)'s HTML5 specification.

Before these HTML5 input types and attributes were available, checking that a phone number doesn't contain alpha characters, or verifying that a properly formed email address has been entered, required that the developer write extra logic for validation. Support for HTML5 client-side form and input validation enables the developer to concentrate on other tasks instead of building validation functions.

New input states support

HTML5 Forms defines several input states for the input element's type attribute. Internet Explorer 10 and Windows apps using JavaScript add support for the URL, Email, and Range states.

Search state

The Search state occurs when you set the input element's type attribute to search. It is identical to the Text state; the only difference is that it is identified in the Document Object Model (DOM) as a "search" input type.

<input id="search" type="search" placeholder="Search..."/>

Telephone state

The Telephone input state, which occurs when you set the input element's type attribute to tel, indicates that the field accepts a telephone number, such as 206-555-0012 or (425) 555-0034. Because telephone numbers can have different formats, the Telephone state does not enforce any one format. If you need to force a particular format, use the pattern attribute.

<input id="work_phone" type="tel" required placeholder="(425) 555-0067"/>

URL and Email states

URL and Email state support offers developers built-in validation for URL and email input types.

The URL input state, which occurs when you set the input element's type attribute to url, indicates that the field must accept a fully qualified web address, such as "https://www.contoso.com".

Similarly, the Email input state accepts only a (syntactically) valid email address, such as "joe@contoso.com". With the following examples, if the user doesn't enter a URL or email address correctly, an error message is displayed.

<input type="url" name="myUrl"/>
<input type="email" name="myEmail"/>

Number states

The Number state occurs when you set the input element's type attribute to number. It requires that the value attribute, if specified and not empty, have a valid floating point number.

<input type="number" name="desiredQuantity" value="1" />

Range state

Support for the Range input state gives you the ability to easily create a range or slider input control. The Range input state occurs when you set the input element's type attribute to range. The range control takes four attributes—min, max, step, and value—to define the value range and resolution of the control. In the example below, a range control is created that returns values of 0 to 100 in increments of 5, with a preset value of 50.

<input type="range" min="0" max="100" step="5" value="50"/>

Because the range control is actually an input element, if it isn't supported in a browser, it will be rendered as a text box with the value inside as a default.

The progress element

The progress element, defined in section 4.10.16 of the HTML5 specification, creates a bar that shows the progress of a task (determinate mode), or shows that a task is running but percentage of completion isn't known (indeterminate mode), or both. For instance, you can start by displaying an indeterminate progress bar and switch to a determinate progress bar after you've calculated how long something will take.

To create a progress indicator that shows just activity, you leave out the value attribute. When you put a value attribute on the element, or assign it a value in script, the bar will become determinate. The bar starts at 0 and goes to the value you set by the max attribute. If you leave out the max attribute, the progress range is from 0 to 1. Both value and max are floating point numbers.

Indeterminate mode syntax

<progress>fallback text</progress>

Determinate mode syntax

<progress id="progCtrl" max="100" value="50">fallback text</progress>

If the user's browser doesn't support the HTML5 progress control, you can put fallback text between the tags (noted here as "fallback text"). You might consider displaying the value of the value attribute as text between the tags. For example, write some script to update the fallback text with something like "The progress of this task is x%", with x representing the current value of the value attribute.

The progress element also has a position attribute that equals the quotient of the value of the value attribute divided by the value of the max attribute, or "-1" if the control is in indeterminate mode. The position attribute is read-only.

Example: Range input state and progress control

The following example combines the Range input state and a progress control. When you first load the page, the progress element is in indeterminate mode (no value assigned). When you move the slider bar, the value to which you move the slider is assigned to the progress control, and they move in sync.

<!DOCTYPE html>
<html>

<head>
<title>Range and progress example</title>
<style type="text/css">
input[type=range] {
  padding-left: 0px;
  padding-right: 0px;
}
</style>
<script type="text/javascript">
  function changeValue() {
    document.getElementById("progCtrl").value = document.getElementById("rangeCtrl").value;
  }
  document.addEventListener('DOMContentLoaded', function () {
    document.getElementById("rangeCtrl").addEventListener('change', changeValue, false);
  }, false);
</script>
</head>

<body>

<progress id="progCtrl" max="100" >Sorry, your browser doesn't support the progress 
element.</progress>
<br><br>
<input id="rangeCtrl" max="100" min="0" step="5" type="range" value="50" />

</body>

</html>

When first loaded, this example appears as follows in Internet Explorer 10 in Windows 8. Notice that the progress bar is in indeterminate mode, which in Windows 8 displays as animated dots that animate in and out of view.

If you move the slider control to the right (to a value of 75), the example appears as follows. The progress bar is now in determinate mode, and has "followed" the slider to match its value.

You can view this page.

Note  Other browsers and operating systems will display the progress bar and slider control differently.

 

For a hands-on demonstration of HTML5 Forms with form and input validation, see HTML5 Forms on the IE Test Drive.

New input attributes support

Support for new HTML5 input attributes such as required, pattern, and placeholder can help developers ensure their users enter the data needed on a webpage, as well as making sure it's the correct data.

The required attribute

The required attribute marks an element that cannot be submitted without a value. The attribute can be set on text, URL, email, select, checkbox, or radio button controls, and on textarea and select elements. It is a Boolean attribute, and need only be specified on an element. When users hover the mouse over a required field, they'll see a tooltip stating that it is a required field. (If you've set the title attribute, that will be shown instead.)

<form id="yourname">
  <label>Enter your first name: 
    <input name="firstname" type="text" required><input type="submit" value="Go"/>
  </label>
</form>

If users try to submit a form without entering something in the field, they'll receive an error message, and the cursor focus will move to the missing field.

The pattern attribute

The pattern attribute allows you to define a regular expression that the user's input must match. The pattern attribute is available on input elements whose type attribute has been set to text, search, url, tel, email, or password

<form>
<label>
  <input type="tel" name="tel" pattern="\(\d\d\d\) \d\d\d\-\d\d\d\d" 
   title="enter a telephone number in   the format (xxx) xxx-xxxx"/>
  <input type="submit"/>
</label>
</form>

The min, max, and step attributes

The min, max, and step attributes are applicable to input controls whose type attribute has been set to number or range. (For more information about range input types, see Range state, elsewhere in this topic.)

The min and max attributes define the minimum and maximum values that will be accepted.

The step attribute defines the allowed interval between values. For example, if min is set to "0" and step is set to "1", then only the values 0, 1, 2, 3, and so on are allowed. Similarly, if min is set to "1.1" and step is set to "1", then only 1.1, 2.1, 3.1, and so on, are allowed.

The following example shows an input field that requires an even number between 0 and 10. Anything outside that range, or an odd number, is not submitted, and an error message is displayed.

<form>
  <label>Enter an even number between 0 and 10: 
    <input type="number" min="0" max="10" step="2"/> 
    <input type="submit"/>
  </label>
</form>

The placeholder attribute and the :-ms-input-placeholder pseudo-class

Often, directing the user to the correct input field and indicating how to enter data can be half the battle of getting valid data. Support for the placeholder attribute enables you to provide guidance to users to enter the correct data into form fields.

The placeholder attribute defines a short prompt or example text to be displayed inside of an input field. It can be used within input controls whose type attribute has been set to text, search, url, tel, email, and password; as well as to textarea elements.

You can use the placeholder attribute to put an example of correct input directly into the input field, as illustrated in the following code snippet.

<input name="url" type="url" placeholder="https://www.contoso.com" />

The markup above will display the placeholder text in the field until the cursor focus is on that field.

By default, the placeholder text is light gray, but you can style it however you want with Cascading Style Sheets (CSS) by using the :-ms-input-placeholder pseudo-class selector. The following example highlights the street and ZIP code fields with a custom style.

<!DOCTYPE html >
<html>
<head>
  <title>Placeholder style example</title>
  <style type="text/css">
  input  /* normal style */
  {
    background-color:LightGray;
    color:Purple;
  }   
  input.address:-ms-input-placeholder /* placeholder only style */   
  {
    font-style:italic;        
    background-color:yellow;
    color:Red;
  }

  </style></head>
<body>
  <form id="test">
    <p><label>Enter Name: <input id="name" placeholder="Your Name"/></label></p>
    <p><label>Enter Street: <input id="street" class="address" 
placeholder="Your address" /></label></p>
    <p><label>Enter a zip code: <input type="num" pattern="(0-9){5}" 
id="zip" class="address" placeholder="5 digit zip" /></label></p>
    <input type="submit" />
  </form>
</body>
</html>

The placeholder text is displayed with the specified style until the field has focus, meaning that the field can be typed into. When the field has focus, it returns to the normal style of the input field and the placeholder text disappears.

You can view this page. (Internet Explorer 10 is required for this page to render correctly.)

The autofocus attribute

The autofocus attribute enables you to guide the user to a specific field by directing focus to a field or control after a webpage loads. This can provide both direction and convenience for a user, and helps reduce the need to click or tab to a form control when a page opens.

Only one control in a document can have autofocus specified. If more than one element has the attribute, only the first one on the page gets the focus when the page opens. This is a Boolean attribute, so it does not need to be set to a value; its presence implies that it is "true".

<input name="email" type="text" placeholder="joe@contoso.com" autofocus />

The novalidate and formnovalidate attributes

The novalidate attribute can be set on form elements that have validation constraints to allow the form to be submitted without validation.

You might want to have multiple submit buttons for a form—for instance, one to submit the form and one to save a partially completed form for the user to come back to later. You can both make the main submit button validate form elements with validation constraints, and prevent the "save for later" button from validating such elements. To do this, instead of setting the novalidate attribute on the entire form, set the formnovalidate attribute on the button that saves the form for later.

The following example shows both attributes in use. The formnovalidate attribute is set on the Save for Later button, while the novalidate attribute is set on the second form element. This means that, in the first form, the Submit button will validate those form elements that have validation constraints, but the Save for Later button will not; and in the second form, no form elements will be validated, regardless of validation constraints.

<!DOCTYPE html>
<html>
<head>
  <title>novalidate and formnovalidate Example</title>
</head>
<body>
  <form>
    <p><label>*Name: <input type="text" required /></label></p>
    <p><label>*Street: <input type="text" required /></label></p>
    <p><label>*Zip: <input type="text" pattern="[0-9](5|10)" placeholder="5 or 9 digit ZIP" required /></label></p>
    <input type="submit" name=submit value="Submit" />
    <input type="submit" formnovalidate name="save" value="Save for Later" />
    <p>* Required field</p>
  </form>
  <form novalidate>
    <p>Unvalidated area</p>
    <p><label>Name: <input type="text" required /></label></p>
    <p><label>Street: <input type="text" required /></label></p>
    <p><label>Zip: <input type="text" pattern= "[0-9](5|10)" placeholder="5 or 9 digit zip" required /></label></p>
    <input type="submit" name=submit value="Submit" />
  </form>
</body>
</html>

Custom validation error messages

Internet Explorer 10 displays several generic messages for a variety of validation errors on input elements. You can customize these messages by using the title attribute on the input element. The content of the title attribute is both shown as tooltip text for the field and appended to the generic pattern mismatch error message. The following example shows how a telephone entry field can provide users with a prompt to indicate how the number should be formatted.

<form>
  <label>Enter a phone number: 
  <input type="text" title="xxx-xxx-xxxx" pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}" />
  <input type="submit" />
  </label>
</form>

If a user leaves out the dashes or types letters into the field, the following response appears. The text "You must use this format: " is automatic.

Caps Lock warning on password fields

To help users figure out more quickly that they are entering the wrong password because the Caps Lock key is on, Internet Explorer 10 and Windows apps using JavaScript add a warning message when focus is in an input field with a type of password and the Caps Lock key is on. No additional coding is required.

Validated fields styling using :valid and :invalid pseudo-classes

Providing users with visual feedback that indicates whether their input is valid can provide a better experience than an error message. Internet Explorer 10 and Windows apps using JavaScript support the CSS pseudo-classes :valid and :invalid. These selectors enable you to style an input field based on the input type or a pattern. For example, a URL field can have a red border around it until a correctly formatted address is entered.

A required field will be invalid until the correct input is entered. A field that isn't required, but has validation, such as a URL field, will be valid until text is entered.

You can also style required or optional fields with the :required and :optional pseudo-classes, respectively. "Required" fields are described in a previous section. "Optional" fields are defined as any input fields that can accept the required attribute but do not have it set, plus any textarea and select elements that don't have the required attribute set.

The following example puts a green border on a field when it is valid and a red border with bold text when it isn't. The email field is required, but the others aren't. The URL field is pre-filled with a bad URL, so it isn't valid when the page opens. In addition, the two optional fields are styled with light gray backgrounds, and the required field with an eye-catching yellow background.

<!DOCTYPE html >
<html>
<head>
  <title>:valid/:invalid Pseudo-class Example</title>
  <style type="text/css">

  #PC1 input:valid { 
    border :solid lime;
    font-weight:normal;
  }
  #PC1 input:invalid { 
    border:solid red;
    font-weight:bold;
  }
  #PC1 input:required{
    background-color:Yellow;
  }
  #PC1 input:optional{
    background-color:LightGray;
  }       
  </style>
</head>
<body>
  <form id="PC1">
    <p><label>Enter some text: <input type="text"/></label></p>
    <p><label>*Enter a valid email address: <input type="email" required /></label></p>
    <p><label>Enter a valid URL: <input type="url" value="not a url"/></label></p>       
    <p>* required field</p>
  </form>
</body>
</html>

When you first start typing an email address into the email address field, it appears as follows.

After you have entered a (syntactically) valid email address, the color of the field's border changes from red to green and the text is no longer boldfaced, as shown here.

When styled like this, the fields provide immediate feedback to the user because they change while the user types.

You can view this page. (Internet Explorer 10 or a browser that supports the form validation pseudo-classes is required for this page to render correctly.)

DOM methods, attributes, and objects for input validation

New APIs have been added to Internet Explorer 10 and Windows apps using JavaScript that enable programmatic access to the validation status of forms and elements using JavaScript.

The checkValidity method [for HTMLFormElement]

The checkValidity method statically validates the constraints (as described in Section 4.10.21.2 of the HTML5 specification) of the form element, and returns "true" if the constraint validation returns a positive result or "false" if it returns a negative result.

The checkValidity method [for HTMLInputElement and all other form elements]

The checkValidity method checks whether the element is valid and returns "true" if it is. Otherwise, it returns "false". If the element is not valid, it also fires a simple invalid event, which is cancelable but has no default event.

The willValidate attribute

The willValidate attribute returns "true" if an element can be validated (such as a url or email input type, or an element with the validation attribute set), and returns "false" otherwise.

The validity attribute

The validity attribute returns a validity state object (ValidityState) for the element. The object is live, and the same object is returned any time the attribute is retrieved.

The validationMessage attribute

The validationMessage attribute returns the error message that is displayed based on the current state of the form. For example, if the form is submitted at that moment, it is invalid.

The setCustomValidity (in DOMString Error) method

The setCustomValidity method sets the custom validity error message for an element.

The ValidityState object

The ValidityState object returns "true" or "false" for the following read-only Boolean attributes:

Attribute Description

valueMissing

The user has not entered a value on a required field.

typeMismatch

The user entered something that is not the correct syntax, such as an incorrectly formatted URL or email address.

patternMismatch

The user entered something that does not match what the pattern attribute specifies, such as letters when numbers were expected.

tooLong

A control has a value that is longer than the maxlength attribute specifies. Because Windows Internet Explorer allows a user to enter only the maxlength number of characters, this usually occurs when the default value contains too many characters.

rangeUnderflow

The user entered a value less than what was specified by the min attribute.

rangeOverflow

The user entered a value greater than what was specified by the max attribute.

stepMismatch

The user entered a value that doesn't correspond to an allowed value as specified by the step and min attributes. For example, the user entered an odd number when even numbers are expected.

customError

The control has a message set by the element's setCustomValidity method (string is not empty).

valid

No other conditions are true.

 

API Reference

:invalid

:optional

:required

:valid

checkValidity

input

progress

setCustomValidity

validationMessage

validity

ValidityState

willValidate

Samples and tutorials

Form controls sample

Form validation sample

Internet Explorer Test Drive demos

Touch First Controls

IEBlog posts

Guidelines for Building Touch-friendly Sites

Specification

HTML5: Section 4.10