Validating User Input in VB.NET: Code Example
VB.NET Code for Input Validation
This code snippet demonstrates a private function in VB.NET designed to validate user input based on different types. The function, named validate
, accepts a string parameter type
and returns a boolean value indicating whether the validation was successful.
Function Structure
The function initializes two variables:
Msg
: A string variable to store error messages.valid
: A boolean variable initialized toTrue
, representing the validation status.
The initial error message is set to:
Msg = "Entry Errors" & vbCrLf & "****************"
Validation Logic
A Select Case
statement is used to determine the type of validation to perform based on the type
parameter.
Case “LOGIN”
This section validates input fields typically found in a login form:
Rut: Checks if
txtRut_I.Text
is empty. If so, adds “You must enter the Rut” toMsg
and setsvalid
toFalse
.Check Digit: Checks if
txtDv_I.Text
is not empty. If it is not empty, it validates whether the entered value is a digit from 0 to 9 or “K” (case-insensitive). If not, it adds “Please enter a valid check digit” toMsg
and setsvalid
toFalse
. IftxtDv_I.Text
is empty, it adds “You must enter the check digit” toMsg
and setsvalid
toFalse
.Name: Checks if
txtNombre_I.Text
is empty. If so, adds “Enter the name” toMsg
and setsvalid
toFalse
.Salary: Checks if
txtSueldo_I.Text
is empty. If so, adds “Enter the salary must Player” toMsg
and setsvalid
toFalse
. If not empty, it further checks if the salary is within the range of $50,000 to $2,000,000. If it is outside this range, it adds “You must enter the value between $50,000 and $2,000,000” toMsg
and setsvalid
toFalse
.Seat: Checks if
cbbPuesto_I.SelectedIndex
is less than or equal to 0. If so, adds “You must select the Seat” toMsg
and setsvalid
toFalse
.
Case “Modify”
This section validates input fields typically used for modifying existing data. The validation logic is similar to the “LOGIN” case, but it uses different field names (txtRut_M
, txtDv_M
, txtNombre_M
, txtSueldo_M
, cbbPuesto_M
).
Case “BUSCAR1”
Initial Value: Checks if
txtValorIni.Text
is empty. If so, adds “You must enter the initial value” toMsg
and setsvalid
toFalse
.Final Value: Checks if
txtValorFin.Text
is empty. If so, adds “Enter the Final Value Must” toMsg
and setsvalid
toFalse
.
Case “BUSCAR2”
Seat: Checks if
cbbPuesto_C.SelectedIndex
is less than or equal to 0. If so, adds “You must select the Seat” toMsg
and setsvalid
toFalse
.
Result
After the Select Case
statement, the function checks the value of valid
. If valid
is False
, it means that at least one validation failed. In this case, it displays a message box with the accumulated error messages (Msg
) and a title of “WARNING”.
Finally, the function returns True
if valid
is False
, and False
otherwise.