Image via istockphoto
Eric Gockel

Written by Eric Gockel

Share

How about saving a server hit for form validation? What I thought was common knowledge, apparently is not. If you haven’t been using the maxlength attribute on your form fields, you don’t know what you’ve been missing.

<input type="text" name="firstname" maxlength="10">

You may have restrictions in your database of 25 characters for a particular field, but why not also put that limit in the form field attributes too? ProActive Validation™ we like to call it. Keep your users from hurting themselves.

[UPDATE: 7/18]

This post originally was written with HTML4 in mind. Fast forward to HTML5 and now we have built-in form validation!

Required Attribute

To make an input required, you can add the “required” attribute to a <input>, <select> or <textarea>. When this is in place, the form won’t submit if the input is empty and will show an error message.

<input type="text" name="usrname" required>

We’ll want to add some CSS to highlight errors when they occur, like this:

input:invalid {
  border: 2px dashed red;
}

Now this simple attribute will only check to see if any value was added, so someone could submit it with an empty space as well. So we’ll need to limits like mentioned above such as maxlength or min to make sure users don’t add to little or too many characters.

Tags
HTML5