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.Textis empty. If so, adds “You must enter the Rut” toMsgand setsvalidtoFalse.Check Digit: Checks if
txtDv_I.Textis 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” toMsgand setsvalidtoFalse. IftxtDv_I.Textis empty, it adds “You must enter the check digit” toMsgand setsvalidtoFalse.Name: Checks if
txtNombre_I.Textis empty. If so, adds “Enter the name” toMsgand setsvalidtoFalse.Salary: Checks if
txtSueldo_I.Textis empty. If so, adds “Enter the salary must Player” toMsgand setsvalidtoFalse. 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” toMsgand setsvalidtoFalse.Seat: Checks if
cbbPuesto_I.SelectedIndexis less than or equal to 0. If so, adds “You must select the Seat” toMsgand setsvalidtoFalse.
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.Textis empty. If so, adds “You must enter the initial value” toMsgand setsvalidtoFalse.Final Value: Checks if
txtValorFin.Textis empty. If so, adds “Enter the Final Value Must” toMsgand setsvalidtoFalse.
Case “BUSCAR2”
Seat: Checks if
cbbPuesto_C.SelectedIndexis less than or equal to 0. If so, adds “You must select the Seat” toMsgand setsvalidtoFalse.
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.
