Member Avatar for Member #719716

I'm trying to add in data validation for my program so it doesnt die when a user input the wrong type of data. eg. My program collects numbers and stores them against the selected name but if i input say fish instead of 2000 in the textbox my program dies.

Could someone let me know how to validate this.

Public Class Form1
    'Declares 2 arrays with a maximum of 4 entries
    Dim strtotals(3) As String
    Dim strsales(3) As String
    Dim intPasswordCounter As Integer = 0


Private Sub btnDisplayTotals_Click(sender As System.Object, e As System.EventArgs) Handles btnDisplayTotals.Click
        'Validate the password first thing, then exit if it returns false
        If Not ValidPassword Then Exit Sub

        ' Variables for handing data        
        Dim strIncomes2(3) As String
        Dim sngSalary(3) As Single
        Dim sngMax As Single
        Dim sngSal As Single
        Dim strEmployee As String
        Dim strTotal(3) As String
        Const Commission As Decimal = 0.015
        Const Pay As Single = 400
        strEmployee = ""
        sngSal = 0
        For i = 0 To 3
            'Calculations
            If strsales(i) <> 0 Then
                strTotal(i) = Str(strsales(i))
                sngSalary(i) = Pay + Int(strsales(i)) * Commission
            Else
                strTotal(i) = 0
                sngSalary(i) = Pay
            End If
            strIncomes2(i) = Str(sngSalary(i))
            If sngSalary(i) > sngSal Then
                sngMax = sngSalary(i)
                strEmployee = lstNames.Items(i)
            End If
            sngSal = sngSalary(i)
            strtotals(i) = "Sales Total for " + lstNames.Items(i) + " is $" + strTotal(i) + " Salary is $" + strIncomes2(i) + vbNewLine
        Next
        lblMessage1.Text = strtotals(0) + strtotals(1) + strtotals(2) + strtotals(3) + "The Highest Salary was $" + Str(sngMax) + " by " + strEmployee
    End Sub

    Private Function ValidPassword() As Boolean

        'Initialize the function to return false.  
        'The return value will only change if the correct password is entered
        ValidPassword = False

        For i = 0 To 2
            Dim strPassword As String = InputBox("Please Enter a Valid Password", "Password Input")
            If strPassword = "admin" Then
                'Got the right password force a return with a value of True
                Return True
            End If
        Next
        'function didn't return yet, so user must have taken too many tries.
        MsgBox("Exceeded maximum attempts... Ending")
        End
    End Function


    Private Sub btnSale_Click(sender As System.Object, e As System.EventArgs) Handles btnSale.Click
        'Sale(lstNames.SelectedIndex).intSales += Val(txtSales.Text)
        For i = 0 To 3
            If lstNames.SelectedIndex = i Then
                strsales(i) = txtSales.Text                   'Stores Sales data with the selected list name
                txtSales.Text = ""
            End If
        Next
    End Sub

    Private Sub btnEnd_Click(sender As System.Object, e As System.EventArgs) Handles btnEnd.Click
        End
    End Sub
End Class

Dani AI

Generated

A few focused fixes will stop the app from “dying” and make the maths reliable.

Validation strategy (where and how)

  • Validate at input time and again before storing. UI-level controls prevent bad data (as suggested: MaskedTextBox or NumericUpDown), but always re-validate programmatically before updating arrays or doing calculations.
  • Prefer typed storage: keep sales in a numeric array (Decimal for currency) instead of strings. That avoids repeated conversions and rounding surprises.
  • Prefer TryParse over IsNumeric (as mentioned). TryParse returns the parsed value and fails cleanly; IsNumeric is less precise and offers no parsed result. Regex (as suggested) is useful for complex patterns but is overkill for simple numeric/currency input.

Practical example (validate, parse, store)

  • Use a small parsing helper that trims input, respects the current culture (decimal separator), and returns a Decimal when valid. Call it from the btnSale_Click handler and reject/notify when parsing fails. Store totals in a Decimal() array and accumulate there.
Dim sales(3) As Decimal

Private Function ParseSalesInput(txt As String, ByRef value As Decimal) As Boolean
    If String.IsNullOrWhiteSpace(txt) Then Return False
    Return Decimal.TryParse(txt.Trim(), Globalization.NumberStyles.Number, Globalization.CultureInfo.CurrentCulture, value)
End Function

' In btnSale_Click:
Dim idx = lstNames.SelectedIndex
If idx < 0 Then MsgBox("Select a name first.") : Return
Dim amount As Decimal
If Not ParseSalesInput(txtSales.Text, amount) Then
    MsgBox("Enter a valid numeric sales amount.") : txtSales.Focus() : Return
End If
sales(idx) += amount
txtSales.Clear()

Additional tips

  • When showing results, format money with value.ToString("C") instead of Str()/Int().
  • Avoid hard-coded array sizes; base loops on lstNames.Items.Count or use a List(Of T).
  • Don’t use End to terminate an app — close the form or call Application.Exit() for a cleaner shutdown.
  • Consider an ErrorProvider or the control Validating event for better UX.

Recommended Answers

All 4 Replies

Member Avatar for Member #1042208

Please state where exactly you wish to validate and what to validate ?

The easiest way would probably be to use a masked textbox wherever you need numbers input.

If that isn't agreeable to you, you can use the .TryParse method of whatever type of number you're looking for. For instance:

Dim TextBoxInput as Integer
Dim ValidateTextBox as Boolean = Integer.TryParse(TextBox1.Text, out TextBoxInput)
If Not ValidateTextBox Then
    TextBox1.Clear
    MsgBox("Input only numbers please")
End If

Or you can check if the textbox input is numeric using IsNumeric() function
Also read this snippet

Member Avatar for Member #1042208

The best way I think is using regular expressions.
First of all include Syste.RegularExpressions in the module.

Copy follwoing code in your module and edit according to your need.

If (Regex.IsMatch(TextBox1.Text, "^[a-zA-Z0-9]+$")) Then
        MsgBox("Valid Character.")
Else
        MsgBox("Invalid Character.")
End If

Regex.IsMatch matches the characters that are permitted to enter. In above example they are smallcase a-z, Uppercase A-Z and Numbers from 1-9.

Note:- Permitted characters have to be in a pair of square bracket []. ^ and +$ marks the beginning and end for matching characters.

TextBox1.Text is text in TextBox1 for which validations are carried out. So you have to change its name to whatever your textbox is.

I hope Rest is self-explanatory.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.