Search code examples
asp.netvb.netserver-side

Server side validation in VB


I am trying to do a server side validation that blocks "^$/()|?+[]{}><" metacharacters Anyone give me some insight on why this . I am new to this :/ (TextBox3 is a asp textboxe that takes input)

Imports System.Text.RegularExpressions

Partial Class Default2
Inherits System.Web.UI.Page

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click

    If Regex.IsMatch(TextBox3.Text, "^$\/()|?+[]{}><") Then
        Label1.Text = "Invalid input"

    End If
End Sub
End Class

ERROR:

 Exception Details: System.ArgumentException: parsing "^$\/()|?+[]{}><" - Unterminated     [] set.

Solution

  • That's because the string ^$\/()|?+[]{}>< is regex metacharacters. You need to escape them before passing to the regex function:

        If Regex.IsMatch(TextBox3.Text, Regex.Escape("^$\/()|?+[]{}><")) Then
            Label1.Text = "Invalid input"
        End If
    

    UPDATED ANSWER:

    2 methods to check if the text contains any of the regex metacharacters:

    Method 1: Using Regex

    The metacharacters need to be put inside a character class [...]. Therefore, only some of the characters need to be escaped, ie: ^, \ and ].

        If Regex.IsMatch(TextBox1.Text, "[\^$\\/()|?+[\]{}><]") Then
            ' Invalid input
        Else
            ' Valid
        End If
    

    Method 2: Using IndexOfAny String function

    This method doesn't use Regex so, there is no need to escape.

        If TextBox1.Text.IndexOfAny("^$\/()|?+[]{}><".ToCharArray) > -1 Then
            ' Invalid input
        Else
            ' Valid
        End If