RequiredFieldValidator with ValidationGroup doesn&

2019-04-10 07:09发布

Here's my markup:

Name: 
<asp:TextBox ID="txtNewName" runat="server" ValidationGroup="NewDepartmentValidationGroup" />
<asp:RequiredFieldValidator ID="vldtxtNewName" runat="server" ControlToValidate="txtNewName"
    ErrorMessage="Required Field" /><br />
Description: 
<asp:TextBox ID="txtNewDescription" runat="server"          
    ValidationGroup="NewDepartmentValidationGroup"/>
<asp:RequiredFieldValidator ID="vldtxtNewDescription" runat="server" 
    ControlToValidate="txtNewDescription" ErrorMessage="Required Field" /><br />
<asp:Button ID="cmdCreate" runat="server" Text="Create"
     ValidationGroup="NewDepartmentValidationGroup" OnClick="cmdCreate_Click" />

When I remove ValidationGroup attribute, the behavior is as expected and the client side code warns that the field is required.

But when I specify ValidationGroup (as noted in the example above) and I click the button with the text boxes empty, the client side code does nothing, the button click event fires and the Page.IsValid equals true and my code proceeds, contrary to what is expected.

Any ideas how to fix this?

2条回答
孤傲高冷的网名
2楼-- · 2019-04-10 07:39

You are missing Validation Group on the Validators.

There's no need to specify validation group on the controls(textboxes) instead specify the validation group on the validators and the button on which you want the valid data to be posted!

Try this one:

    Name: 
<asp:TextBox ID="txtNewName" runat="server" />
<asp:RequiredFieldValidator ID="vldtxtNewName" runat="server"
     ControlToValidate="txtNewName" ValidationGroup="NewDepartmentValidationGroup" 
     ErrorMessage="Required Field" /><br />
Description: 
<asp:TextBox ID="txtNewDescription" runat="server" />
<asp:RequiredFieldValidator ID="vldtxtNewDescription" runat="server" 
    ControlToValidate="txtNewDescription" ErrorMessage="Required Field"
    ValidationGroup="NewDepartmentValidationGroup" /><br />
<asp:Button ID="cmdCreate" runat="server" Text="Create"
     ValidationGroup="NewDepartmentValidationGroup" OnClick="cmdCreate_Click" />
查看更多
Viruses.
3楼-- · 2019-04-10 07:48

try with ValidationGroup="NewDepartmentValidationGroup" in the validators not in textbox

<asp:TextBox ID="txtNewName" runat="server"  />
        <asp:RequiredFieldValidator ID="vldtxtNewName" runat="server" ControlToValidate="txtNewName"  ValidationGroup="NewDepartmentValidationGroup"
            ErrorMessage="Required Field" /><br />
Description: 
<asp:TextBox ID="txtNewDescription" runat="server"          
    />

<asp:RequiredFieldValidator ID="vldtxtNewDescription" runat="server" 
    ControlToValidate="txtNewDescription" ErrorMessage="Required Field" ValidationGroup="NewDepartmentValidationGroup"/><br />

<asp:Button ID="cmdCreate" runat="server" Text="Create"
      ValidationGroup="NewDepartmentValidationGroup" OnClick="cmdCreate_Click" causesvalidation="true" />
查看更多
登录 后发表回答