Database design for dynamic form field validation

大城市里の小女人 提交于 2019-12-11 12:02:48

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/3910250/database-design-for-dynamic-form-field-validation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!