Search code examples
vb.netvalidationtimetextbox

Set up a TextBox that accepts only a range of times


I need to insert in a textbox the time intervals with the format hh:mm/hh:mm (e.g., 08:00/13:00, 14:00/18:00) to set the reception times of a specific user.

How can I do this by also entering a control on the time entered (if I enter 25:60/70:90, it must not be accepted because the timetable does not exist). Thanks in advance!


Solution

  • Another option would be to use TimeSpan.TryParseExact. This will give you the same result and it also allows you to easily get the time values as TimeSpans so you can use them for further calculations or for storing them somewhere, for example.

    Private Sub TextBox1_Validating(sender As Object, e As System.ComponentModel.CancelEventArgs) Handles TextBox1.Validating
        Dim validRange As Boolean = False
        Dim time1, time2 As TimeSpan
    
        Dim timeRanges As String() = TextBox1.Text.Split("/"c)
        If timeRanges.Length = 2 Then
            If TimeSpan.TryParseExact(timeRanges(0), "hh\:mm",
                                      Globalization.CultureInfo.InvariantCulture, time1) AndAlso
               TimeSpan.TryParseExact(timeRanges(1), "hh\:mm",
                                      Globalization.CultureInfo.InvariantCulture, time2) Then
                validRange = True
            End If
        End If
    
        If validRange Then
            ' Use `time` and `time2` for anything you want.
        Else
            ' TODO: Indicate to the user that they entered an invalid input.
            e.Cancel = True
        End If
    End Sub
    

    Edit:

    If you don't want to manually type : and /, you can use a MaskedTextBox instead of a TextBox.

    First, after adding a MaskedTextBox onto your form, set its Mask property to 00:00/00:00:

    MaskedTextBox.Mask

    Then you can adjust the code above to work with a MaskedTextBox like this:

    Private Sub MaskedTextBox1_Validating(sender As Object, e As System.ComponentModel.CancelEventArgs) Handles MaskedTextBox1.Validating
        Dim validRange As Boolean = False
        Dim time1, time2 As TimeSpan
    
        Dim timeRanges As String() = MaskedTextBox1.Text.Split("/"c)
        If MaskedTextBox1.MaskCompleted Then
            If TimeSpan.TryParseExact(timeRanges(0), "hh\:mm",
                                      Globalization.CultureInfo.InvariantCulture, time1) AndAlso
               TimeSpan.TryParseExact(timeRanges(1), "hh\:mm",
                                      Globalization.CultureInfo.InvariantCulture, time2) Then
                validRange = True
            End If
        End If
    
        If validRange Then
            ' Use `time` and `time2` for anything you want.
        Else
            ' TODO: Indicate to the user that they entered an invalid input.
            e.Cancel = True
        End If
    End Sub