views:

36

answers:

1

In my application, I allow users to create a form containing any HTML form field they want (e.g. text input, textarea, select, etc.). I want to give the users the ability to define 0 or more cumulative validation rules for each field (there might be up to 25 different validation rules). How should I model this?

Here's a potential solution:

============================================================
| Id | FieldId | ValidationRuleType | ValidationRuleDetail |
============================================================
| 1  | 25      | Required           | NULL                 |
------------------------------------------------------------
| 2  | 26      | Minimum Length     | 5                    |
------------------------------------------------------------
| 3  | 26      | Maximum Length     | 12                   |
------------------------------------------------------------
...

Using the above design, maybe in most cases, the ValidationRuleType could just be "Regex" (or a value from a lookup table, such as ValidationRuleTypeId = 1 for "Regex"), and use the following for ValidationRuleDetail:

// Added bonus of this approach is that users who know regex could define their own patterns
.{1,}  // Any character, 1 or more times. Use for "Required"
.{5,}  // Any character, 5 or more times. Use for "Minimum Length = 5"
.{,12} // Any character, 12 or less times. Use for "Maximum Length = 12"

The problem is that this solution is EAV. That's a bad thing, right?

Another potential solution:

=============================================================
| Id | FieldId | Required | Minimum Length | Maximum Length |
=============================================================
| 1  | 25      | TRUE     | NULL           | NULL           |
-------------------------------------------------------------
| 2  | 26      | NULL     | 5              | 12             |
-------------------------------------------------------------
...

Is this better? I'm conflicted on which approach to use. Any guidance I can get is much appreciated.

A: 

The answer depends entirely on how you want the validation rules to work. If all you are going to have is required/min/max, then they should just be columns for the field (last option). If a validation rule defines a specific set of dynamic rules, they should be in their own table and a mapping between a validation rule and the field ID should exist (you should be able to map the same field ID to multiple validation rules in this case). Then you query for the fields, join with the mapping table and join with the rules to apply the rules to that field.

tandu