我有一个页面,上面有两个文本框,上面有正则表达式。
ASPX 代码文本框 1
<asp:TextBox ID="txtCasesInsert" runat="server" Width="50px"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvCases" ControlToValidate="txtCasesInsert" ValidationGroup="InsertRecord"
runat="server" ErrorMessage="*" ForeColor="Red"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="regexCases" ControlToValidate="txtCasesInsert"
ValidationExpression="[0-9]+(,[0-9]+)*" ForeColor="Red" ErrorMessage="Please seperate numbers with a comma"
runat="server" />
ASPX 代码文本框 2
<asp:TextBox ID="txtPremiumInsert" runat="server" Width="50px"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvPremium" ControlToValidate="txtPremiumInsert"
ValidationGroup="InsertRecord" runat="server" ErrorMessage="*" ForeColor="Red"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="regexPremium" ControlToValidate="txtPremiumInsert"
ValidationExpression="[0-9]+(,[0-9]+)*" ForeColor="Red" ErrorMessage="Please seperate numbers with a comma"
runat="server" />
正则表达式对两个文本框都按预期工作。
我现在需要的是能够检查输入到这些文本框中的文本,如果正则表达式有效,则启用我的插入按钮,否则,保持按钮禁用。
插入按钮
<asp:Button ID="btnInsertRecord" Width="100px" Height="25px" runat="server" Text="Add Record"
CssClass="buttonBlue" ValidationGroup="InsertRecord" />
我想这样做的原因是,当正则表达式出错时,页面仍然允许用户插入数据,所以我想如果正则表达式不成功则禁用按钮以防止这种情况发生。
我试过这个C# If regex doesn't match then do something并且我还阅读了 Microsoft 的 Regex 文档以了解更多关于我可以用 Regex 做什么的信息,但我没有找到任何与我需要的信息相关的信息。
我还尝试使用连接到文本框的 TextChanged 方法创建一个函数,但它不起作用。没有错误消息,只是当我输入错误的字符串时按钮没有禁用。这也是我现在使用当前代码时遇到的问题。就像什么事都没有发生一样。我已经将调试器挂在了_premiumMatch.Success
线上,但又一次,什么也没发生,它只是让我继续。当我为我的按钮创建 TextChanged 方法时,我还尝试将它添加到我的页面加载方法中,但这会立即禁用按钮。
当前 VB 代码(带有文本框之一的示例)
Dim _regex As Regex = New Regex("[0-9]+(,[0-9]+)*")
Dim _premiumMatch = _regex.Match(txtPremiumInsert.Text)
If _premiumMatch.Success Then
Try
Company.Applications.ProductionEngine.BusinessAccess.ExcelFileContentUploadBusinessAccess.InsertLimitInsurance(_branch,
_premium,
_cases,
_ddlMonths,
_ddlYear)
Catch ex As Exception
InformationBox.ShowErrorMessage("Record not added. Please try again")
End Try
loadLimitInsurances()
InformationBox.ShowSuccessMessage("New Record Inserted")
txtBranchInsert.Text = ""
txtPremiumInsert.Text = ""
txtCasesInsert.Text = ""
End If
不知道我做错了什么。有什么建议么?上面的 VB 代码现在在我的按钮单击事件中,但即使使用无效的正则表达式,当我单击插入时仍会执行。
第一次编辑 刚刚尝试在我的页面加载中调用以下函数,但是如果我输入有效的正则表达式,该按钮会立即禁用并且不会启用。同样,示例适用于一个文本框。
Protected Friend Sub CheckPremium() Handles txtPremiumInsert.TextChanged
Dim _regex As Regex = New Regex("[0-9]+(,[0-9]+)*")
Dim _match As Match = _regex.Match(txtPremiumInsert.Text)
If _match.Success Then
btnInsertRecord.Enabled = True
Else
btnInsertRecord.Enabled = False
End If
End Sub
第二次编辑
我已经尝试了上面的代码并且我已经AutoPostBack
在文本框上激活了,当我输入一个无效的表达式时,它仍然回发并激活我的按钮。