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
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.
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
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;
}
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
System.Web.UI.WebControls.BaseValidator
and employing client-side and server-side validation functions. (bounty added)