New form elements, attributes, input types, browser-based validation, CSS3 style technology, and FormData objects make creating forms easier and perhaps even more fun.
Browser support
When you write this article, all new forms and input elements as well as attributes and types of support will vary greatly depending on the browser. Even among browsers that support a particular feature, they behave differently. However, support for HTML5 forms has changed rapidly and continues to improve. At the time of this writing, these charts are the latest charts I can find, detailing how each browser supports HTML5 forms.
What's new overview
New element
HTML5 introduces 5 new elements for input and form.
Element Purpose annotation
Progress is used to indicate that the task is complete. The progress element can be used to represent the upload process for a file.
Meter is used to represent scalar measurements within a known range. The meter element can be used to indicate measured values such as temperature or weight.
DataList is used to represent a set of option elements that you can use with the new Input property list to make a Drop-down menu. If you focus to input with a datasheet, the system displays a Drop-down menu that contains the values in the DataList.
Keygen the control used to generate the key pair. When submitting a form, the private key is saved in the local keystore and the public key is sent to the server.
Output is used to display the results of calculations. For example, an output element can be used to display the sum of two input element values.
New input type
HTML5 introduced 13 new input types. If viewed in browsers that do not support these input types, the system uses backing text input.
input type Purpose note
Tel is used to enter phone numbers. Tel does not perform specific syntax, so if you want to ensure a particular format, you can use pattern or setcustomvalidity () to perform additional validation.
Search is used to prompt the user for text to search for. The difference between search and text is mainly in the style. Using the search input type may cause the style of the input field to match the platform's search field.
URL is used to enter a single URL. The URL is used to enter a single absolute URL that represents a large range of values.
Email is used to enter a single e-mail address or e-mail address list. If you specify the multiple property, you can enter multiple e-mail addresses, separated by commas.
DateTime is used to enter the date and time when the time zone is set to UTC.
Date is used to enter dates that do not contain the time zone.
Month is used to enter dates that contain the year and month but do not contain the time zone.
Week is used to enter dates with years and weeks but no time zone. For example, the date in this format 2011-w05 represents the 5th week of 2011.
Time is used to enter a fraction of the hours, minutes, seconds, and seconds, but not including the timezone.
Datetime-local is used to enter a date and time that does not contain a time zone.
Number is used to enter numbers. Valid values are floating-point numbers.
Range is used to enter numbers, but the difference from number is that you do not need to enter specific numbers. In most browsers that support this type, the scope control is implemented as a slider.
Color is used to select colors from a color pool control. The value must be a valid lowercase simple color, such as a #ffffff.
New Input Properties
HTML5 also introduces several new attributes for input and form elements.
Attribute Purpose Comment
Autofocus is used to focus the input on the related element after the Web page is loaded. The autofocus target can be input, selection, text area, and buttons.
Placeholder is used to prompt the user for the type of data that should be entered. The system displays placeholder values in light-colored text before focusing on the relevant elements and before the user enters data. You can specify this value in the input and text areas.
form is used to specify one or more forms to which the input element belongs. With the form property, you can place an INPUT element anywhere on a Web page, rather than in a form element. Also, a single input element can be associated with more than one form.
Required the Boolean attribute used to represent a required element. The Required property helps you perform browser-based validation without using custom JavaScript.
AutoComplete is used to specify that browsers should not automatically populate or populate a field based on the user's history. The AutoComplete property can be used for fields that you do not want to automatically populate, such as credit card numbers or one-time passwords. By default, AutoComplete is on, so if you want to deactivate the property, set it to off.
Pattern is used to validate the value of an element based on a regular expression. When using pattern, you should also specify a title value to provide a description of the expected schema to the user.
DirName is used in the direction of submitting controls with the form. For example, if the user enters text data in right-to-left direction, and the INPUT element contains the DirName property, the system submits the indicated Right-to-left orientation along with the input value.
Novalidate specify this property on a FORM element to deactivate form submission validation.
FormAction is used to overwrite the action attribute on a FORM element. The input and button elements support this property.
Formenctype is used to overwrite enctype properties on form elements. The input and button elements support this property.
FormMethod is used to overwrite the method attribute on a FORM element. The input and button elements support this property.
Formnovalidate is used to overwrite novalidate properties on form elements. The input and button elements support this property.
Formtarget is used to overwrite the target attribute on a FORM element. The input and button elements support this property.
FormData objects
One of the many improvements to XMLHttpRequest is the introduction of the FormData object. With the FormData object, you can create and send a set of key/value pairs, or you can choose to create and send files using XMLHttpRequest. When you use this technique, the data is sent in the same format as the data that you submit through the submit () method with the Multipart/form-data encoding type of the form.
FormData provides a way for you to create HTML forms instantly using JavaScript, and then submit the form using Xmlhttprequest.send (). The following is a simple example:
var formData = new FormData ();
Formdata.append ("Part_num", "123ABC");
Formdata.append ("Part_price", 7.95);
Formdata.append ("Part_image", Somefile)
var xhr = new XMLHttpRequest ();
Xhr.open ("POST", "http://some.url/");
Xhr.send (FormData);
You can also add additional data to an existing form by using FormData before submitting the form.
var formelement = document.getElementById ("someformelement");
var formData = new FormData (formelement);
Formdata.append ("Part_description", "The best part ever!");
var xhr = new XMLHttpRequest ();
Xhr.open ("POST", "http://some.url/");
Xhr.send (FormData);
Browser-based validation
To be honest, validating form data is a very annoying task, but you have to do it anyway. Now, in order to perform client form validation, you might write custom JavaScript code or use libraries to perform certain actions, such as checking for valid input or ensuring that required fields are filled out before the form is submitted.
New input properties, such as required and pattern, used with CSS pseudo class selectors make it easier for you to write inspection code and show feedback to the user. With some other advanced validation techniques, you can also use JavaScript to set custom validation rules and messages, or to determine whether an element is invalid and why.
Required Property
When you submit a form, the field with the required property must contain a value. The following examples of required e-mail address input fields are used to ensure that the field contains a value that is a valid e-mail address (click here for a specific definition).
<input type= "Email" id= "email_addr" name= "email_addr" required/>
Pattern Properties
You can specify the regular expression used to validate the input field through the Pattern property. This example represents a required text input field for a part number. In this example, we assume that the part number consists of three uppercase letters and four digits immediately following it. Use required and pattern to ensure that the field contains a value that conforms to the correct format for the part number. If the user hovers the mouse over the field, the system displays the message in the title property.
<input type= ' text ' id= ' part ' name= ' part ' required pattern= ' [a-z]{3}[0-9]{4} ' title= ' part numbers consist of 3 Uppercas E letters followed by 4 digits. " />
On the basis of this example, if you enter a part number that is not valid, you can also paint the border of the input field in red. To display a red border around the input field if the value is not valid, add the following CSS.
: Invalid {
border:2px solid #ff0000;
}
Formnovalidate Property
The Formnovalidate property applies to input or button elements. Use this property to deactivate form submission validation. In the following example, submitting the form through the Submit button requires valid input, but is not required to submit through the Save button.
<input type = "text" = name = required = title = /> <
input
type="submit" formnovalidate value="Save"> <
input
type="submit" value="Submit">
Constraint Validation API
The constraint validation API provides you with powerful tools to handle custom validation. You can use this API to perform actions such as setting custom errors, checking if an element is valid, and determining why an element is not valid. In the following example, if the values in the two fields are inconsistent, the system displays a custom error.
<label>Email:</label>
<input type= "Email" id= "email_addr" name= "email_addr" >
<label>repeat Email address:</label>
<input type= "Email" id= "email_addr_repeat" name= "email_addr_repeat" oninput= "Check (this)" >
<script>
function check (input) {
if (Input.value!= document.getElementById (' email_addr '). Value) {
Input.setcustomvalidity (' The two email addresses must match. ')
} else {
Input is valid--Reset of the error message
Input.setcustomvalidity (");
}
}
</script>
Comprehensive use
The following booking Request Form example combines various input types, form validation, and CSS selectors and styles.
The HTML and JavaScript for the form are as follows:
<form oninput= "Total.value = (Nights.valueasnumber * 99) +
((guests.valueasnumber-1) * ">
<label>full name:</label>
<input type= "text" id= "Full_name" name= "Full_name" placeholder= "Jane Doe" required>
<label>email address:</label>
<input type= "Email" id= "email_addr" name= "Email_addr" required>
<label>repeat Email address:</label>
<input type= "Email" id= "email_addr_repeat" name= "email_addr_repeat" required
oninput= "Check (this)" >
<label>arrival date:</label>
<input type= "Date" id= "Arrival_dt" name= "Arrival_dt" required>
<label>number of nights (rooms are $99.00 per night):</label>
<input type= "number" id= "Nights" name= "Nights" value= "1" min= "1" max= "required>"
<label>number of guests (additional guest adds $10.00 per night):</label>
<input type= "number" id= "guests" name= "guests" value= "1" min= "1" max= "4" required>
<label>estimated total:</label>
$<output id= "Total" name= "Total" >99</output>.00
<br><br>
<label>promo code:</label>
<input type= "text" id= "promo" name= "promo" pattern= "[A-za-z0-9]{6}"
title= "Promo codes consist of 6 alphanumeric characters." >
<input type= "Submit" value= "Request reservation"/>
</form>
<script>
function check (input) {
if (Input.value!= document.getElementById (' email_addr '). Value) {
Input.setcustomvalidity (' The two email addresses must match. ')
} else {
Input is valid--Reset of the error message
Input.setcustomvalidity (");
}
}
</script>
The form code takes the following CSS:
: Invalid {
Border-color: #e88;
-webkit-box-shadow:0 0 5px Rgba (255, 0, 0,. 8);
box-shadow:0 0 5px Rgba (255, 0, 0,. 8);
}
: Required {
Border-color: #88a;
-webkit-box-shadow:0 0 5px rgba (0, 0, 255,. 5);
box-shadow:0 0 5px rgba (0, 0, 255,. 5);
}
form {
width:300px;
margin:20px Auto;
}
Input {
font-family: "Helvetica neue", Helvetica, Arial, Sans-serif;
border:1px solid #ccc;
font-size:20px;
width:300px;
min-height:30px;
Display:block;
margin-bottom:15px;
margin-top:5px;
Outline:none;
-webkit-border-radius:5px;
border-radius:5px;
}
Input[type=submit] {
Background:none;
padding:10px;
}