在按钮中添加OnClientClick时,必需的字段验证器不起作用

时间:2013-06-14 09:40:39

标签: c# asp.net requiredfieldvalidator

我有一个RequiredFieldValidator像这样

<asp:TextBox ID="txtEmployeeID" runat="server" MaxLength="255" CssClass="txt" 
    OnTextChanged="txtEmployeeID_TextChanged" AutoPostBack="True" 
    ValidationGroup="Save" ></asp:TextBox>     
<asp:RequiredFieldValidator ID="rfvEmployeeID" runat="server" 
    ErrorMessage="Employee ID is required information."
    ControlToValidate="txtEmployeeID" Display="None" ValidationGroup="Save"
    SetFocusOnError="True"></asp:RequiredFieldValidator>

和这样的按钮

 <asp:Button ID="btnBlockUser" runat="server" Text="Block User" 
    CssClass="submitBtn " OnClick="btnBlockUser_Click" 
    OnClientClick="javascript:return confirm('Are you sure want to Block this user ?')"
    ValidationGroup="Save" />

现在的问题是,如果我删除按钮中的OnClientClick,RequriedFieldValidator工作正常如果我把它放回那里页面帖子没有显示任何错误消息可以解释为什么会发生这种情况?

1 个答案:

答案 0 :(得分:27)

尝试使用此代码,它会帮助您

    <asp:RequiredFieldValidator ID="rfvEmployeeID" runat="server" ErrorMessage="Employee ID is required information."
        ControlToValidate="txtEmployeeID"  ValidationGroup="Save" SetFocusOnError="True"></asp:RequiredFieldValidator>
        <br />
    <asp:Button ID="btnBlockUser" runat="server" Text="Block User" CssClass="submitBtn"  CausesValidation="true"  OnClientClick="return validate();" 
        OnClick="btnBlockUser_Click" ValidationGroup="Save" />
        <script type="text/javascript" language="javascript" >
            function validate() {
                if (Page_ClientValidate())
                return confirm('Are you sure want to Block this user ?');
            }
        </script>