Validation (better)

Tags
Summary

Wrap a bunch of individual checks inside the flag pattern.

Situation

You have several pieces of data to check. You want to show all the errors at once.

Needs

Several pieces of data you don't trust.

Provides

Checked data you can work with.

Action

Use the flag pattern to wrap as many validation checks as you want. Example:

  • tIsInputOk = "yes"
  •  
  • 'Validate meal cost
  • tUncheckedUserInput = Cells(1, 2)
  • If Not IsNumeric(tUncheckedUserInput) Then
  •     'Not numeric, show error.
  •     Cells(1, 3) = "Sorry, meal cost must be a number."
  •     Cells(1, 3).Font.Color = vbRed
  •     tIsInputOk = "no"
  • Else
  •     'Is numeric.
  •     sMealCost = tUncheckedUserInput
  •     If sMealCost < 0 Then
  •         Cells(1, 3) = "Sorry, meal cost cannot be negative."
  •         Cells(1, 3).Font.Color = vbRed
  •         tIsInputOk = "no"
  •     End If
  • End If
  •  
  • 'Validate tip rate
  • tUncheckedUserInput = Cells(2, 2)
  • If Not IsNumeric(tUncheckedUserInput) Then
  •     'Not numeric, show error.
  •     Cells(2, 3) = "Sorry, tip rate must be a number."
  •     Cells(2, 3).Font.Color = vbRed
  •     tIsInputOk = "no"
  • Else
  •     'Is numeric.
  •     sTipRate = tUncheckedUserInput
  •     If sTpRate < 0 Then
  •         Cells(2, 3) = "Sorry, tip rate cannot be negative."
  •         Cells(2, 3).Font.Color = vbRed
  •         tIsInputOk = "no"
  •     End If
  • End If
  •  
  • 'Did anything go wrong?
  • If tIsInputOk = "no" Then
  •     End
  • End If
Where referenced