When doing validation in JavaScript, how do I keep validation methods that need to handle a bunch of contingencies from becoming unruly?
For example, I have a form with a field that has validation that checks:
- is the new value a number?
- Is the value in another field on the
form > 0 when the current field > 0 - Is another field on the form == 1 and
the current field == 0 - Is another field on the form == true
and the current field is Mod another
field == 0
Etc.
Currently, I’ve got a method with a bunch of if/else statements.
I could break each check out into it’s own method and call it from the main validation method, but that would create a ton of new methods.
Update: regardless of whether I use a framework or individual methods, am I still resigned to having the calling validation method filled with If/Else or Switch statements with alert boxes for the failing validations?
Sounds like you might want a rudimentary state machine. One thing you might consider is breaking the validators into the simplest forms:
Then you can chain them together to form more complex systems.
You’ll still have a lot of code, but if you do it right, functions should be small and easy to understand.