Asp.net中的RegularExpressionValidator

时间:2014-02-08 20:02:42

标签: asp.net

我有搜索文本框,其默认值为Enter Month to View Profit。当我单击搜索按钮而不输入任何数据时,文本框的默认值将发布到服务器以进行搜索。我希望RegularExpressionValidator不验证文本框的默认值。

<asp:TextBox ID="Tboxsearch" Text="Enter Month to View Profit" OnClick="this.value=''"  CssClass="textboxinput" runat="server"></asp:TextBox>
    <asp:Button ID="ButtonSearch" CssClass="btnLog" runat="server" Text="Search" onclick="ButtonSearch_Click" />
    <asp:RequiredFieldValidator   
                             ID="RequiredFieldValidatorname"  
                             runat="server"  
                             ControlToValidate="Tboxsearch" 
                             ForeColor="Red"                            
                             Text="*"  
                             >  
                        </asp:RequiredFieldValidator>  
                        <asp:RegularExpressionValidator   
                            ID="RegularExpressionValidatorname"  
                            runat="server"   
                            ValidationExpression="[a-zA-Z0-9]+"
                            ForeColor="Red"  
                            ControlToValidate="Tboxsearch"  
                            ErrorMessage="Enter Valid Name!"  
                            >  
                        </asp:RegularExpressionValidator>

1 个答案:

答案 0 :(得分:1)

除了RequiredFieldValidator控件之外的所有验证器的默认值,如果使用空字段发布验证器将不会触发

您必须使用必需的字段验证器和其他验证器来阻止回发发生

来自MSDN

Special-Case Validation Results for ASP.NET Server Controls

修改

此外,如果您在问题中添加控件,它应该可以工作,但如果有其他控件,例如其他按钮,您应该将validationGroup属性设置为您想要一起工作的组

ValidationGroup="vGrp"

,您的代码就像这样

<asp:TextBox ID="Tboxsearch" Text="Enter Month to View Profit" OnClick="this.value=''" CssClass="textboxinput" runat="server" ValidationGroup="vGrp"></asp:TextBox>
<asp:Button ID="ButtonSearch" CssClass="btnLog" runat="server" Text="Search" onclick="ButtonSearch_Click" ValidationGroup="vGrp" />
<asp:RequiredFieldValidator
    ID="RequiredFieldValidatorname"
    runat="server"
    ControlToValidate="Tboxsearch"
    ForeColor="Red"
    Text="*"
    ValidationGroup="vGrp">  
</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator
    ID="RegularExpressionValidatorname"
    runat="server"
    ValidationExpression="[a-zA-Z0-9]+"
    ForeColor="Red"
    ControlToValidate="Tboxsearch"
    ErrorMessage="Enter Valid Name!" ValidationGroup="vGrp"></asp:RegularExpressionValidator>
来自MSDN的

关于validationGroup