The Complete Guide to HTML Forms and Constraint Validation


In this article, we look at HTML form fields and the validation options offered by HTML5. We’ll also look at how these can be enhanced through the use of CSS and JavaScript.

What is Constraint Validation?

Every form field has a purpose. And this purpose is often governed by contraints — or the rules governing what should and shouldn’t be entered into each form field. For example, an email field will require a valid email address; a password field might require certain types of characters and have a minimum number of required characters; and a text field might have a limit on how many characters can be entered.

Modern browsers have the ability to check that these constraints are being observed by users, and can warn them when those rules have been breached. This is known as contstraint validation.

Client-side vs Server-side Validation

The majority of JavaScript code written in the early years of the language handled client-side form validation. Even today, developers spend significant time writing functions to check field values. Is this still necessary in modern browsers? Probably not. In most cases, it really depends on what you’re trying to do.

But first, here’s a big warning message:

Client-side validation is a nicety which can prevent common data-entry errors before an app wastes time and bandwidth sending data to a server. It’s not a substitute for server-side validation!

Always sanitize data server-side. Not every request will come from a browser. Even when it does, there’s no guarantee the browser validated the data. Anyone who knows how to open a browser’s developer tools can also bypass your lovingly crafted HTML and JavaScript.

HTML5 Input Fields

HTML offers:

<textarea> for multiline text boxes
<select> for a drop-down list of options
<button> for … buttons

But you’ll use <input> most often:

<input type=”text” name=”username” />

The type attribute sets the control type, and there’s a large choice of options:

type
description
button
a button with no default behavior
checkbox
a check/tick box
color
a color picker
date
a date picker for the year, month, and day
datetime-local
a date and time picker
email
an email entry field
file
a file picker
hidden
a hidden field
image
a button which displays the image defined by the src attribute
month
a month and year picker
number
a number entry field
password
a password entry field with obscured text
radio
a radio button
range
a slider control
reset
a button that resets all form inputs to their default values (but avoid using this, as it’s rarely useful)
search
a search entry field
submit
a form submission button
tel
a telephone number entry field
text
a text entry field
time
a time picker with no time zone
url
a URL entry field
week
a week number and year picker

The browser falls back to text if you omit the type attribute or it doesn’t support an option. Modern browsers have good support for all types, but old browsers will still show a text entry field.

Other useful <input> attributes include:

attribute
description
accept
file upload type
alt
alternative text for the image types
autocomplete
hint for field auto-completion
autofocus
focus field on page load
capture
media capture input method
checked
checkbox/radio is checked
disabled
disable the control (it won’t be validated or have its value submitted)
form
associate with a form using this ID
formaction
URL for submission on submit and image buttons
inputmode
data type hint
list
ID of <datalist> autocomplete options
max
maximum value
maxlength
maximum string length
min
minimum value
minlength
minimum string length
name
name of control, as submitted to server
pattern
a regular expression pattern, such as [A-Z]+ for one or more uppercase characters
placeholder
placeholder text when the field value is empty
readonly
the field is not editable, but it will still be validated and submitted
required
the field is required
size
the size of the control (often overridden in CSS)
spellcheck
set true or false spell-checking
src
image URL
step
incremental values in numbers and ranges
type
field type (see above)
value
the initial value

HTML Output Fields

As well as input types, HTML5 provides read-only outputs:

output: a text result of a calculation or user action
progress: a progress bar with value and max attributes
meter: a scale which can change between green, amber, and red depending on the values set for the value, min, max, low, high, and optimum attributes.

Input Labels

Fields should have an associated <label>, which you can wrap around the element:

<label>your name <input type=”text” name=”name” /><label>

Or link the field’s id to the label using a for attribute:

<label for=”nameid”>your name</label>
<input type=”text” id=”nameid” name=”name” />

Labels are important for accessibility. You may have encountered forms which use a placeholder to save screen space:

<input type=”text” name=”name” value=”” placeholder=”your name” />

The placeholder text disappears once the user types something — even a single space. It’s better to show a label than force the user remember what the field wanted!

Input Behaviors

Field types and constraint attributes change the browser’s input behavior. For example, a number input shows a numeric keyboard on mobile devices. The field may show a spinner and keyboard up/down cursor presses will increment and decrement values.

Most field types are obvious, but there are exceptions. For example, credit cards are numeric, but the increment/decrement spinner is useless and it’s too easy to press up or down when entering a 16-digit number. It’s better to use a standard text type, but set the inputmode attribute to numeric, which shows an appropriate keyboard. Setting autocomplete=”cc-number” also suggests any pre-configured or previously entered card numbers.

Using the correct field type and autocorrect offers benefits which would be difficult to achieve in JavaScript. For example, some mobile browsers can:

import credit card details by scanning a card using the camera
import one-time-codes sent by SMS

Automatic Validation

The browser ensures an input value adheres with the constraints defined by the type, min, max, step, minlength, maxlength, pattern, and required attributes. For example:

<input type=”number” min=”1″ max=”100″ required />

Attempting to submit an empty value prevents form submission and shows the following message in Chrome:

The spinners will not permit values outside the 1 to 100 range. Similar validation messages appear if you type a string which is not a number. All without a single line of JavaScript.

You can stop browser validation by:

adding a novalidate attribute to the <form> element
adding a formnovalidate attribute to the submission button or image

Creating Custom JavaScript Inputs

If you’re writing a new JavaScript-based date entry component, please stop and step away from your keyboard!

Writing custom input controls is difficult. You have to consider the mouse, keyboard, touch, speech, accessibility, screen dimensions, and what happens when JavaScript fails. You’re also creating a different user experience. Perhaps your control is superior to the standard date picker on desktop, iOS, and Android, but the unfamiliar UI will confuse some users.

There are three primary reasons developers choose to create JavaScript-based inputs.

1. Standard controls are difficult to style

CSS styling is limited and often requires hacks, such as overlaying an input with its label’s ::before and ::after pseudo-elements. The situation is improving, but question any design which prioritizes form over function.

2. Modern <input> types are not supported in old browsers

In essence, you’re coding for Internet Explorer. IE users won’t get a date picker but can still enter dates in YYYY-MM-DD format. If your client insists, then load a polyfill in IE only. There’s no need to burden modern browsers.

3. You require a new input type which has never been implemented before

These situations are rare, but always start with appropriate HTML5 fields. They’re fast, and they work even before the script has loaded. You can progressively enhance fields as necessary. For example, a sprinkling of JavaScript can ensure a calendar event’s end date occurs after a starting date.

In summary: avoid re-inventing HTML controls!

Continue reading
The Complete Guide to HTML Forms and Constraint Validation
on SitePoint.

Leave a Comment

Your email address will not be published.

Scroll to Top