Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What pattern for deeply nested web form validation?

I'm refactoring a large legacy web application that has some complicated forms.

These forms use javascript to display or hide fields on the basis of other entered fields. E.g ticking a checkbox for "second address" reveals a set of other fields to enter.

The current validation for this consists of lots of deeply nested if statements. Similar to:

if(checkboxTicked) {
  haveMandatoryAddressFieldsBeenEntered();
   if(addressHasbeenFilledIn) {
        validateAddress()
   }
}

Now imagine this example with much deeper nesting!

My question is - is there a nice pattern or best practice that I can refactor this with?

For reference I'm using Spring MVC - but I guess this would apply across multiple technologies.

like image 934
Pablojim Avatar asked Jun 05 '26 08:06

Pablojim


1 Answers

When using MVC, I put my validation in my model. The model and controller don't know about how the form in the view looks like.

like image 113
Paco Avatar answered Jun 07 '26 22:06

Paco