I’m working on a phone number search feature where users can enter numbers in different formats. For example, if someone searches for (555) 123-4567
, the database might contain entries like:
5551234567
15551234567
555-123-4567
555 123 4567
555.123.4567
I need to clean both the search input and build a SQL query that strips unwanted characters. Here’s my current VB.NET code:
Dim charactersToStrip() As String = {"+", "-", "(", ")", ".", " ", ","}
Dim searchNumber As String = txtPhoneInput.Text.Trim()
Dim sqlColumn As String = "ContactPhone"
For Each character As String In charactersToStrip
searchNumber = searchNumber.Replace(character, "")
sqlColumn = String.Format("REPLACE({0}, '{1}', ''))", sqlColumn, character)
Next
If Not (String.IsNullOrEmpty(searchNumber)) Then
If (String.IsNullOrEmpty(queryString)) Then
queryString = String.Format(" {0} LIKE '{1}'", sqlColumn, searchNumber)
Else
queryString = String.Format("{0} AND {1} LIKE '{2}'", queryString, sqlColumn, searchNumber)
End If
End If
The problem happens when building the nested REPLACE functions in this line:
sqlColumn = String.Format("REPLACE({0}, '{1}', ''))", sqlColumn, character)
I get an error saying “Input string was not in a correct format.” What’s wrong with my string formatting approach?