2

I want to validate an ASP textbox for unbalanced parenthesis. Like i want to display an error if the user starts a curly bracket but does not end it in a textbox.

Thanks

4
  • Do you want to use a server-side or client-side function? Or doesn't it matter? Commented Jun 17, 2011 at 14:35
  • Do you need that only for the beginning curly bracket or for any nested bracket too? Commented Jun 17, 2011 at 15:01
  • I think this question could be really useful for reference if someone could develop a nice example inheriting System.Web.UI.WebControls.BaseValidator and employing client-side and server-side validation functions. (bounty added) Commented Jun 20, 2011 at 20:48
  • @abhinav - I've posted a solution that includes client-side.
    – Peter
    Commented Jun 22, 2011 at 14:54

3 Answers 3

2

Inherit from the asp:BaseValidator control.

Override the Validate() method to go through character by character and increment a counter for each ( and decrement for each ). If the counter ever goes negative or end up at anything other than 0, you are unbalanced.

Use the RegisterValidatorCommonScript method to put a javascript method to the page for client-side validation. The javascript method will use the same logic.

1
  • This answer will integrate code similar to mine below into the builtin page validation functionality (therefore you can use .IsValid as normal) +1 Would be nice to see a javascript example since I am not very good with client side. Commented Jun 17, 2011 at 18:10
1

Here is a rough example using server-side code in VB.

Markup:

<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Label ID="Label1" runat="server" Text="Unequal number of curly brackets {} found." Visible="false"></asp:Label>
<asp:Button ID="Button1" runat="server" Text="Button" />

Code:

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
    If ValidateCurlyBrackets(TextBox1.Text) Then
        Label1.Visible = False
        'Do submit action
    Else
        Label1.Visible = True
    End If
End Sub

Protected Function ValidateCurlyBrackets(ByVal Text As String) As Boolean
    Dim intOpen As Integer = 0
    For Each c As Char In Text
        If c = "{" Then
            intOpen += 1
        ElseIf c = "}" Then
            If intOpen < 1 Then
                Return False
            Else
                intOpen -= 1
            End If
        End If
    Next
    If intOpen = 0 Then
        Return True
    Else
        Return False
    End If
End Function
1
  • Can we have a client side function.
    – abhinav
    Commented Jun 20, 2011 at 18:21
1
+50

I created a class that inherits from BaseValidator which performs both server side and client side validation. I also added an option so that you can specify what type of "Enclosure" to use, so it's not just restricted to {}, you can use any character for opening and any character for closing.

Code:

'I used the site "http://www.eighty-twenty.net/stories/2007/10/15/aspNetCustomValidators.html" as a reference'
Public Class EnclosedTextValidator
    Inherits System.Web.UI.WebControls.BaseValidator

    Public Property EnclosureOpening As String
        Get
            If ViewState("EnclosureOpening") Is Nothing Then
                Return "{"
            Else
                Return ViewState("EnclosureOpening").ToString()
            End If
        End Get
        Set(value As String)
            If value.Length > 1 Then Throw New Exception("Only single character opeing enclosures allowed")
            ViewState("EnclosureOpening") = value
        End Set
    End Property

    Public Property EnclosureClosing As String
        Get
            If ViewState("EnclosureClosing") Is Nothing Then
                Return "}"
            Else
                Return ViewState("EnclosureClosing").ToString()
            End If
        End Get
        Set(value As String)
            If value.Length > 1 Then Throw New Exception("Only single character closing enclosures allowed")
            ViewState("EnclosureClosing") = value
        End Set
    End Property

    Protected Overrides Function EvaluateIsValid() As Boolean
        Dim val = GetControlValidationValue(Me.ControlToValidate)

        Dim intOpen As Integer = 0

        For Each c As Char In val
            If c = EnclosureOpening Then
                intOpen += 1
            ElseIf c = EnclosureClosing Then
                intOpen -= 1

                If intOpen < 0 Then
                    Return False
                End If
            End If
        Next

        Return intOpen = 0
    End Function

    Protected Overrides Sub AddAttributesToRender(writer As System.Web.UI.HtmlTextWriter)
        MyBase.AddAttributesToRender(writer)

        Page.ClientScript.RegisterExpandoAttribute(ClientID, "evaluationfunction", "CheckEnclosures")
        Page.ClientScript.RegisterExpandoAttribute(ClientID, "EnclosureOpening", EnclosureOpening)
        Page.ClientScript.RegisterExpandoAttribute(ClientID, "EnclosureClosing", EnclosureClosing)
    End Sub

    Protected Overrides Sub OnPreRender(e As System.EventArgs)
        MyBase.OnPreRender(e)

        If EnableClientScript And Not Page.ClientScript.IsClientScriptBlockRegistered("EnclosedTextValidator") Then
            Page.ClientScript.RegisterClientScriptBlock( _
                GetType(EnclosedTextValidator), "EnclosedTextValidator", "<script type=""text/javascript"">" + Environment.NewLine + _
                    "function CheckEnclosures(val) {" + Environment.NewLine + _
                        "var value = ValidatorGetValue(val.controltovalidate);" + Environment.NewLine + _
                        "var intOpen = 0;" + Environment.NewLine + _
                        "var result = false;" + Environment.NewLine + _
                        "for(var i=0;i<value.length;i++) {" + Environment.NewLine + _
                            "var c = value.substring(i, i+1);" + Environment.NewLine + _
                            "if (c == val.EnclosureOpening) {" + Environment.NewLine + _
                                "intOpen++;" + Environment.NewLine + _
                            "} else if (c== val.EnclosureClosing) {" + Environment.NewLine + _
                                "intOpen--;" + Environment.NewLine + _
                                "if(intOpen < 0) {result = false; break;}" + Environment.NewLine + _
                            "}" + Environment.NewLine + _
                        "}" + Environment.NewLine + _
                        "result = intOpen == 0;" + Environment.NewLine + _
                        "if (result == false) {" + Environment.NewLine + _
                            "var errorMsg = ""Unequal number of "" + val.EnclosureOpening + val.EnclosureClosing + "" enclosures found. "";" + Environment.NewLine + _
                            "if (val.innerText) {" + Environment.NewLine + _
                                "val.innerText = errorMsg;" + Environment.NewLine + _
                            "} else {" + Environment.NewLine + _
                                "val.textContent = errorMsg;" + Environment.NewLine + _
                            "}" + Environment.NewLine + _
                        "}" + Environment.NewLine + _
                        "return result;" + Environment.NewLine + _
                    "}" + Environment.NewLine + _
            "</script>")
        End If
    End Sub
End Class

Use:

Here is an example of validating the textbox "txt". I changed the enclosure type to () instead of {}, but the default is still {} if you dont' specify. I also enabled the client side check. Note that right now the error message for client side is hard coded (though it does adjust slightly depending on the enclosure characters) but is trivial to change by adjusting the javascript that is rendered in the OnPreRender sub.

<asp:TextBox ID="txt" runat="server" />
<web:EnclosedTextValidator runat="server" ID="cvEnclosure" 
        EnableClientScript="true" ControlToValidate="txt" EnclosureOpening="(" EnclosureClosing=")"
         Text="ERROR" />
<asp:Button ID="btnTestValidatioN" runat="server" Text="Test Validation" />

for reference, here is the javascript by itself:

function CheckEnclosures(val) {
        var value = ValidatorGetValue(val.controltovalidate);
        var intOpen = 0;
        var result = false;

        for(var i=0;i<value.length;i++) {
            var c = value.substring(i, i+1);

            if (c == val.EnclosureOpening) {
                intOpen++;
            } else if (c== val.EnclosureClosing) {
                intOpen--;
                if(intOpen < 0) {result = false; break;}
            }
        }

        result = intOpen == 0;

        if (result == false) {
            var errorMsg = "Unequal number of " + val.EnclosureOpening + val.EnclosureClosing + " enclosures found. ";
            if (val.innerText) {
                val.innerText = errorMsg;
            } else {
                val.textContent = errorMsg;
            }
        }

        return result;
    }
5
  • I think there is a problem with the line if(intOpen < 1) {result = false; break;}, first of all I think it should be if (intOpen < 0), and second I'm not sure how break; works but the client side validator shows "ERROR" as the message and does not prevent postback if there are more closes than opens. Server side validation still works properly in that case however. Other than that everything seems to work fine! Commented Jun 22, 2011 at 14:43
  • Break means to stop looping immediately. So we stop after encountering the first issue. This equivelant to "continue" in vb.net. In looking at the code I'm trying to think if you are right or not about the intOpen < 1... Just test it and tweak it as needed. If you say it should be 0 I will change it.
    – Peter
    Commented Jun 22, 2011 at 14:46
  • In looking at the code I see that my code behind is intOpen <0 and my javascript is intOpen <1. I'm going to say it's supposed to be <0 as you suggested.
    – Peter
    Commented Jun 22, 2011 at 14:52
  • Can i have a client side javascript function
    – abhinav
    Commented Jun 22, 2011 at 19:41
  • As the code stands right now, no, but it would be easy to add. Just add a new property (we'll call it 'CustomClientFunction') and then change the line that says 'Page.ClientScript.RegisterExpandoAttribute(ClientID, "evaluationfunction", "CheckEnclosures")' and put an inline check in place of the "CheckEnclosures" constant. Something like: 'if(not string.isnullorempty(CustomClientFunction),CustomClientFunction, "CheckEnclosures")
    – Peter
    Commented Jun 22, 2011 at 21:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.