Caesium95
Caesium95

Reputation: 579

How to call a public function from another form

Frm1 contains the code for validation of textbox:

Public Function AlphabeticalOnly(ByVal Str As String) As Boolean
    Dim pattern As String = "^[a-zA-Z\s]+$"
    Dim reg As New Regex(pattern)
    If reg.IsMatch(Str) = False Then
        MsgBox(Str & " is invalid! Please enter alphabetical characters only!", MsgBoxStyle.Critical, "Error")
    End If
    Return reg.IsMatch(Str)
End Function

Because there're quite an amount of validations, I don't want to repeat all the code again in the other forms.

Private Sub btnDone_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDone.Click
If AlphabeticalOnly(txtName.Text) = False Then
        Exit Sub
End If
...
End Sub

I tried the code above in another form, but the error list shows that AlphabeticalOnly is not declared.

Is there anything that I need to add to my code?

Upvotes: 1

Views: 9041

Answers (1)

David
David

Reputation: 218827

First of all, don't put the function on a form. If it's common code shared by all forms, put it in its own class file.

Second, this common code shouldn't be prompting the user with a message box. This function should just perform the logic and nothing more. (This also makes the function easier to unit test.) Then allow the consuming code (in this case a form) to interact with the user. (Especially since the current implementation checks the match twice, which isn't necessary.)

Since this function doesn't rely on object state, you can make it Shared. Something like this:

Public Class CommonFunctions
    Public Shared Function IsAlphabeticalOnly(ByVal Str As String) As Boolean
        Dim pattern As String = "^[a-zA-Z\s]+$"
        Dim reg As New Regex(pattern)
        Return reg.IsMatch(Str)
    End Function
End Class

Then on your forms you can invoke that function:

If CommonFunctions.IsAlphabeticalOnly(txtName.Text) = False Then
    MsgBox(Str & " is invalid! Please enter alphabetical characters only!", MsgBoxStyle.Critical, "Error")
End If

Upvotes: 4

Related Questions