Question Correct Function ?

inkedgfx

Well-known member
Joined
Sep 29, 2012
Messages
139
Location
USA
Programming Experience
Beginner
I wrote a function to validate that the user has filled in some textbox's ...the function I wrote works , just wondering is this is the correct way to do this.

  Private Function ValidateText() As Boolean
        Dim isEmpty As Boolean = False
        If Me.txtFirstName.Text = "" Or Me.txtLastName.Text = "" Then
            isEmpty = True
        Else
            isEmpty = False
        End If
        Return isEmpty
    End Function


should I put the txt variables between the "()" or is this ok as is?

InkedGFX
 
As far as that code is concerned, there's nothing actually wrong with it but there are a couple of things that are suboptimal.

The most obvious issue is the fact you are using Or. You should always use AndAlso and OrElse as the default Boolean operators in VB.NET and only use And and Or when you specifically need to avoid short-circuiting, which should pretty much never be the case.

The second issue is that you're setting isEmpty to False in two different places, which is pointless. With an If...Else statement, you are setting the value of isEmpty whether the TextBoxes are populated or not, so initialising the variables is pointless. If you are going to initialise the variable to False then you only to set it if the value is to be True, so you don't need the Else block.

Finally, it's also worth noting that that whole method body could be replaced with this:
Return Me.txtFirstName.TextLength > 0 AndAlso Me.txtLastName.TextLength > 0
Having said all that, that's not really the "proper" way to perform validation. Each TextBox has Validating and Validated events that obviously relate to validation. The intended way to validate a control is to handle its Validating event and then set e.Cancel to True if the contents fails validation. That will stop the user leaving the control until they enter valid data. When the user clicks an OK button or you are otherwise ready to make use of the data, you call ValidateChildren on the form, which will raise the Validating event for every control, including the ones that have not yet received focus. It will return True if every control passes validation and False otherwise, indicating whether it is safe to use the data or not.
 
Thank You for the reply...I will remember not to use Or and And in the future.....

InkedGFX
 
Back
Top