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?
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:
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.
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.