2

I have a single form field that asks for "Full Name" when the user signs up. I want to then split that string into first name and then surname. I can get that working with the following code:

<%
If Request.Form("user[username]") <> "" Then
     NameStr = Request.Form("user[username]")
     Dim WordArray
     WordArray = Split(NameStr, " ")
End If
%>

From that I can then split the variables into my form with:

value="<%=WordArray(0)%>"
value="<%=WordArray(1)%>"

However, if the user just puts their first name in I get an error as the Split is looking for a space between the words to perform the action correctly. I have tried:

<%
If Request.Form("user[username]") <> "" Then
    NameStr = Request.Form("user[username]")
    Dim WordArray
            If NameStr = "" Then
                    WordArray = Split(NameStr, "")
            Else
                    WordArray = Split(NameStr, " ")
            End If
End If
%>

Now I knew this would fail as it will never be blank but is there a way to look to see if the Split will error if there is only a first name and no surname? I have looked at validating the form field but cannot see a way of ensuring it has a space between them.

Any ideas?

Nick Green
  • 428
  • 3
  • 8
  • 18

2 Answers2

2

Split is not the problem. If the string doesn't have a space in it, Split won't throw an error, but will return an array with only one element. What you should do is check the upper bound of WordArray using the UBound function:

Dim WordArray, firstName, lastName
WordArray = Split(NameStr, " ")

firstName = WordArray(0)
If UBound(WordArray) >= 1 Then
    lastName = WordArray(1)
Else
    lastName = ""
End If
Cheran Shunmugavel
  • 8,319
  • 1
  • 33
  • 40
  • Perfect. Thanks. I managed to get it working as per my own answer yesterday however I think your solution is a better one. – Nick Green Nov 16 '12 at 11:32
-1

It's not really a fix, but I managed some "old school" VBA techniques and it has at least trapped the error:

<%
If Request.Form("user[username]") <> "" Then
    NameStr = Request.Form("user[username]")
    Dim WordArray
        WordArray = Split(NameStr, " ")
        On Error Resume Next
End If
%>

The On Error Resume Next just ignores the error and moves on. Dirty (just like ASP is, but it works!).

Nick Green
  • 428
  • 3
  • 8
  • 18