john
john

Reputation: 11

Decimal Dots validation on VB textbox

Under keypress event, I have a function validating the entered characters, this is my code.

Public Function vNum2(val As Object)

    Dim result As Boolean = False
    Dim allowedChars As String = "0123456789." & vbBack
    Try


        If allowedChars.IndexOf(val) = -1 Then
            result = True
        End If


    Catch ex As Exception
        MsgBox("Error 1010xVNum2: " & ex.Message)
    End Try

    Return result

End Function

How do i validate a decimal when I entered more than 2 dots in decimal? When I press another dot, the textbox will not receive the character.

E.g: -> correct entry 45.23 receive the first dot. -> validating entry 45.2.3 will not receive the next dot.

Upvotes: 0

Views: 129

Answers (1)

nelek
nelek

Reputation: 4312

Try this :

Public Function vNum2(val As Object)
        Dim result As Boolean = False
        Try
            'Dim allowedChars As String = "42.2.3"
            Dim allowedChars As String = val.ToString()
            'Bellow line will count how many dots are in string, if there one or none, result will be True
            If allowedChars.Where(Function(dots) dots = ".").Count < 2 Then result = True
        Catch ex As Exception
            MsgBox("Error 1010xVNum2: " & ex.Message)
        End Try
        Return result
    End Function

Upvotes: 1

Related Questions