我如何在asp中验证不平衡括号中的文本框

时间:2011-06-17 14:22:22

标签: asp.net

我想验证ASP文本框的不平衡括号。就像我想在用户启动大括号但不在文本框中结束时显示错误。

由于

3 个答案:

答案 0 :(得分:2)

继承asp:BaseValidator控件。

重写Validate()方法逐个字符,并为每个方法增加一个计数器(并为每个方法递减)。如果计数器变为负数或以0以外的任何值结束,则表示您处于不平衡状态。

使用RegisterValidatorCommonScript方法将javascript方法放到页面以进行客户端验证。 javascript方法将使用相同的逻辑。

答案 1 :(得分:1)

这是一个在VB中使用服务器端代码的粗略示例。

标记:

<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" />

代码:

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

答案 2 :(得分:1)

我创建了一个继承自BaseValidator的类,它执行服务器端和客户端验证。我还添加了一个选项,以便您可以指定要使用的“Enclosure”类型,因此它不仅限于{},您可以使用任何字符进行打开,任何字符都可以用于关闭。

代码:

'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

使用:

以下是验证文本框“txt”的示例。我将机箱类型更改为()而不是{},但如果您未指定,则默认值仍为{}。我还启用了客户端检查。请注意,现在客户端的错误消息是硬编码的(尽管它会根据机箱字符稍微调整一下),但通过调整OnPreRender子中呈现的javascript来进行更改是微不足道的。

<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" />

供参考,这里是javascript本身:

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;
    }