Input Patterns in HTML

Very, very, very early this morning I read “Digit is not a number” by Krzysztof Trzewiczek. He describes a problem that web developers can run into if they treat a Credit Verification Value (CVV) as if it were a number. I suggest you read his short post before continuing with mine. You will see that Trzewiczek offers the idea of using tel URIs to force numeric input. To be frank: that is a bad idea. Not only does it make no semantic sense, it still does not restrict user input to only numbers (which the author admits) because tel URIs can have non-numeric characters.

A better approach is to use something I don’t see often enough: the pattern attribute of the <input> tag.

Lots of Useful Attributes

The <input> tag has a great set of attributes which you can use to refine your forms. The pattern attribute lets you provide a JavaScript regular expression which tells the browser that the input must match that expression. Note well that the pattern is always case-sensitive.

So here is an example for CVV’s:

<input name="cvv"
       title="A three-digit Credit Verification Value" />

Note: The type is not necessary, but personally I would use it in this situation.

The regular expression given to the pattern attribute is simple: it says that the value must be exactly three digits. It is not necessary to use anchors because browsers will always apply the pattern to the entire input value. In other words, the browser treats our pattern as if we had written ^(?:[0-9]{3})$.

The attribute is straight-forward. But I want to point out the title attribute. When used in conjunction with pattern, the title attribute describes the format or nature of that input value. Some browsers and other user agents will display this information, such as via a tool-tip. So personally I recommend always providing a title attribute with a useful description of the pattern.

Finally, let me stress that this is not an acceptable replacement for input validation. Just because input conforms to a pattern does not mean you should ever automatically trust it. Think of the pattern attribute as a way to help out your users, not yourself as a developer, because you still need to perform validation and sanity-checking on the server-side regardless.

Posted in Web

One thought on “Input Patterns in HTML

Add Your Thoughts

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s