Hi peoples,

I have a textbox:

<asp:TextBox 
     ID="TextBoxFirstName" 
     runat="server">
</asp:TextBox>

I need to make sure that it captures data for a first name allowing letters from a-z, A-Z and special characters like - (dash) and the space characters. The validator will block all other characters. How do I go about doing this using VB (if possible).

Cheers

Dani AI

Generated

wanted server-side VB validation for a first-name field (letters plus dash and space). was right to suggest a regex-based validator for quick client feedback, but client-side checks can be bypassed and the expression in that post has issues. A practical approach is: enforce the same rule on the server (VB) and mirror it client-side for UX.

A simple, robust VB function using .NET regex:

Imports System.Text.RegularExpressions

Private Function IsValidFirstName(name As String) As Boolean
    If String.IsNullOrWhiteSpace(name) Then Return False
    name = name.Trim()
    Dim pattern As String = "^[A-Za-z][A-Za-z \-]{0,39}$"  ' 1..40 chars; letters, spaces and hyphens
    Return Regex.IsMatch(name, pattern)
End Function

Call that from your submit handler and show an error when it returns False:

Protected Sub btnSubmit_Click(sender As Object, e As EventArgs)
    If Not IsValidFirstName(txtFirstName.Text) Then
        ' display error, set focus, prevent processing
    End If
End Sub

Notes and edge cases:

  • If you need international names (accents, non-Latin letters), use a Unicode-aware pattern like "^[\p{L}][\p{L} -']{0,39}$" instead of plain A-Z.
  • Decide whether to allow apostrophes or multiple consecutive spaces/hyphens and extend the pattern accordingly.
  • Never rely only on client-side validators: always validate on the server. Also normalize (Trim) and HtmlEncode output when rendering user data to avoid XSS.
  • For regex details and .NET usage, see Microsofts Regex reference and the Regex.IsMatch docs: Regular expression language quick reference and Regex.IsMatch.
<asp:TextBox ID="txtName" runat="server"/>
    <asp:Button ID="btnSubmit" runat="server" Text="Submit" />
    <asp:RegularExpressionValidator ID="regexpName" runat="server"     
                                    ErrorMessage="This expression does not validate." 
                                    ControlToValidate="txtName"     
                                    ValidationExpression="^[a-zA-Z'(.|_|' ')\s]{1,40}$" />
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.