0

I am trying to validate data ranges using the select case statement. I am having issues with the other nested select cases. Is this possible or am i wishfull thinking? Or should i separate the select case statements to be stacked?

For instance this is my code in vb:

Select Case intyear
    Case 2000 To 2025
        Select Case intmonth
            Case 1 To 12
                BlnDateValid = True
        End Select
        Select Case intDay
            Case 1 To 31
                BlnDateValid = True
        End Select
        Select Case intHours
            Case 0 To 23
                BlnDateValid = True
        End Select
        Select Case intAddDays
            Case 0 To 60
                BlnDateValid = True
        End Select
        Select Case intAddHours
            Case 0 To 23
                BlnDateValid = True
        End Select
    Case Else
        BlnDateValid = False
End Select


If blnDatevalid = false then
    MessagebBox.Show("Please check all fields and enter valid 
data", "Invalid data", MessageBoxButtons.OK)
jmcilhinney
  • 50,448
  • 5
  • 26
  • 46

2 Answers2

0

Unfortunately, the indenting making sense doesn't help the code make sense. The whole point of Select Case is to neatly select one of multiple cases. A Select Case with one case is bad code and you should be using an If statement instead. You should especially be using a If statement in this case because you can replace all those Select Case statements with a single If statement.

If Not (intyear >= 2000 AndAlso intyear <= 2025 AndAlso
        intmonth >= 1 AndAlso intmonth <= 12 AndAlso
        intDay >= 1 AndAlso intDay <= 31 AndAlso
        intHours >= 0 AndAlso intHours <= 23 AndAlso
        intAddDays >= 0 AndAlso intAddDays <= 60 AndAlso
        intAddHours >= 0 AndAlso intAddHours <= 23) Then
    MessagebBox.Show("Please check all fields and enter valid data", "Invalid data", MessageBoxButtons.OK)
End If
jmcilhinney
  • 50,448
  • 5
  • 26
  • 46
0

All the Select or If checks will still leave you vulnerable to non-sensical values like February 30. Better to actually attempt to create a DateTime value.

Dim d As DateTime
Dim t As TimeSpan
Try
    d = New DateTime(intYear, intMonth, intDay, intHours, 0, 0)
    t = New TimeSpan(intAddDays, intAddHours, 0, 0)
    If t > (New TimeSpan(60, 23, 0, 0)) Then Throw New ArgumentOutOfRangeException() 
Catch
    MessagebBox.Show("Please check all fields and enter valid data", "Invalid data", MessageBoxButtons.OK)
End Try

or you can create a string and try parsing it:

If Not DateTime.TryParse($"{intYear}-{intMonth}-{intDay} {intHours}:00:00")
    MessagebBox.Show("Please check all fields and enter valid data", "Invalid data", MessageBoxButtons.OK)
End If
Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794