by May 19, 2011

Module Monday: Field Validation

Field Validation is a new arrival to the Drupal module directory: its 1st release was just a week ago, and it's designed for Drupal 7's new Field API. What does it do? Field Validation allows you to add simple validation rules to custom Drupal fields, using a simple UI.

The module was inspired by Webform Validation, which adds similar validation to WebForm components. Right now, only basic regular expression validation rules are supported support but the module provides hooks for implementing other validation rules.

One common application is enforcing a certain format for information entered into a text field. Product codes or employee ID numbers are common examples. In the instructions below, we'll assume that the "id_number" field needs to be restricted to '12-abcd' style entries -- two numbers, a dash, then four letters.

First, create a textfield field called id_number and edit the field. Then, add a new Regular Expression validation rule.

null

Next, fill out the settings form for the field. The regular expression should look like this: ^[0-9]{2}-[a-z]{4}$.

null

Save the form, and add a new piece of content for the node type you added the field to. When I filled it out, I used the text 'abc-1234' -- as you can see, it displays the error message we specified for the validation rule.

null

Finally, try it with a valid id. II used '07-eric' -- lucky for me, my name is only four characters! This time around, the node should save without any validation errors.

If you're new to the world of regular expressions, sites like Regular Expressions Info provide libraries of useful regex patterns that can be used for validation. That's about all you can do with the Field Validationmodule right now: it's a young module, but definitely one to keep an eye on!