Visual Basic Code Snippet - Validate (int) Integer

Visual Basic Code Snippet - Validate (int) Integer

Visual Basic Code Snippet - Validate (int) Integer

(VB) Visual Basic code snippets return the validated int value by checking validity of the given int and checking the int value range within the given minimum and maximum int range.

Bookmark:

Visual Basic Code Snippet - Validate (int) Integer

These .Net Visual Basic code snippets validate given int number. This method takes 4 arguments. Int value to validate, default value in case given value is not a valid int, minimum int value and maximum int value. Integer value read as a object which allows to pass the value in any form such as text, data reader value, int, object ..etc. Value will be check against the maximum and minimum value to make sure given value is in correct range. If the given value is less than minimum value, method will return the given minimum value. If the given value is greater than maximum value, method will return the given maximum value. In any case if the given value is not a valid int value, then default value will be return.

''' <summary>
''' Validate given integer value
''' </summary>
''' <param name="_Data">pass int value to validate</param>
''' <param name="_DefaultVal">default int value</param>
''' <param name="_MinVal">Minimum int value allowed</param>
''' <param name="_MaxVal">Maximum int value allowed</param>
''' <returns>Validated int value</returns>
Public Function ValidateInt(ByVal _Data As Object, ByVal _DefaultVal As Integer, ByVal _MinVal As Integer, ByVal _MaxVal As Integer) As Integer
    Dim _val As Integer = _DefaultVal

    Try
        If _Data IsNot Nothing Then
            _val = Integer.Parse(_Data.ToString())

            If _val < _MinVal Then
                _val = _MinVal
            ElseIf _val > _MaxVal Then
                _val = _MaxVal
            End If
        End If
    Catch _Exception As Exception
        ' Error occured while trying to validate

        ' set default value if we ran into a error
        _val = _DefaultVal

        ' You can debug for the error here
        Console.WriteLine("Error : " & _Exception.Message)
    End Try

    Return _val
End Function


Here is a simple example showing how to use above function (ValidateInt) to validate int. In this example shows how to validate entered int value in textbox when user leaving textbox.

'' Check the int value when user leaving the textbox after entering value
Private Sub TextBox1_Leave(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.Leave
    TextBox1.Text = ValidateInt(TextBox1.Text, 10, 5, 20).ToString()
End Sub


VB Keywords Used:

  • int
  • int.Parse
  • Exception

Code Snippet Information:

  • Applies To: Visual Studio, .Net, VB, Visual Basic, CLI, Validate numbers, Validate integers
  • Programming Language : Visual Basic (VB)

External Resources:

Leave a comment