4

I need to validate some form inputs in complex way. E.g.

<select id="options" multiple="multiple">  
<option>A</option>  
<option>B</option>  
<option>C</option>  
<option>D</option>  
<option>E</option>  
</select>  

For example, if user selects A and B, user should be given an error if user also selects D.

Note, I'm trying to keep this business rule in a separate layer from this UI code, which could be an entirely different form, e.g. checkboxes, drag-and-drop, add/delete options with possibly accompanying fields.

I'm looking for a framework, design pattern, or other elegant way to code this logic, preferably ultimately through validation attributes in a model.

3 Answers3

1

Approaching the question from a different angle: Why not disable D if the user selects A and B? When I have this kind of question I start to think about reviewing my UI flow.

1

For representing the validation logic of your inputs, you can use a Karnaugh map, in which inputs are the selection state of A, B, C, D and E, and the outcome is the validation status of each input combination.

  AB-CDE | 000 | 001 | 011 | 010 | 110 | 111 | 101 | 100 |
 --------+-----+-----+-----+-----+-----+-----+-----+-----+
  00     |     |     |     |     |     |     |     |     |
 --------+-----+-----+-----+-----+-----+-----+-----+-----+
  01     |     |     |     |     |     |     |     |     |
 --------+-----+-----+-----+-----+-----+-----+-----+-----+
  11     |     |     |  0  |  0  |  0  |  0  |     |     | -> Error if (A.B).D
 --------+-----+-----+-----+-----+-----+-----+-----+-----+
  10     |     |     |     |     |     |     |     |     |
 --------+-----+-----+-----+-----+-----+-----+-----+-----+

From that map, you can find the minimal logic expression validating your check boxes.

mouviciel
  • 15,491
0

Most frameworks can validate at the model level. So that should be sufficient. So you validate at the lowest possible level.

Example: https://stackoverflow.com/questions/14217442/cakephp-validation-depending-on-other-field

If you want to show this in the interface (with ajax for example) you just call the model to validate (via the controller probably). Create a method in the controller like: validateOptions() and send an ajax call to it so you can modify the user interface.

When really saving the validation will be done again to ensure it's right.

Luc Franken
  • 2,874