简体   繁体   中英

Custom Validator controls don't stop the page from being submitted

I have a GridView on my page that has Validation controls (require and regular expression) on the input fields of the Edit template. Basically, I'm validating the user submitted inputs when they click "Edit" in a GridView.

Here's some sample markup:

<asp:TemplateField HeaderText="Name" SortExpression="Name">
    <EditItemTemplate>
        <asp:TextBox ID="EditFacultyName" runat="server" Text='<%# Bind("Name") %>' 
            CausesValidation="True"></asp:TextBox>
        <br />
        <asp:RequiredFieldValidator ID="EditFacultyNameRequired" runat="server" 
            ControlToValidate="EditFacultyName" ErrorMessage="You must provide a name" 
            ValidationGroup="ValidateGridView" Display="Dynamic"></asp:RequiredFieldValidator>
        <asp:RegularExpressionValidator ValidationExpression="^[a-zA-Z0-9 ]*$" 
            ID="EditFacultyNameRegex" runat="server" 
            ControlToValidate="EditFacultyName" 
            ErrorMessage="Must be alphanumeric characters and spaces" Display="Dynamic" ValidationGroup="ValidateGridView"></asp:RegularExpressionValidator>
    </EditItemTemplate>
    <ItemTemplate>
        <asp:Label ID="Label1" runat="server" Text='<%# Bind("Name") %>'></asp:Label>
    </ItemTemplate>
</asp:TemplateField>

The validation controls fire when I lose focus to the input element, but they won't stop the page from being submitted if I click "Update" in the GridView.

I've made a more graphic example.

在此处输入图片说明

Here you can that the Name field is empty, and the Location field contains invalid characters. The validation controls show me an error, but when I click Update (circled in red) they still go through and get added to the database.

How can I stop that from happening?

Thanks!

You will need to check the page's IsValid property in your update event handler in your server-side code. It's a good practice to do this in addition to the client-side validation, because a malicious user could easily bypass client-side validation.

protected void OnUpdate(object sender, EventArgs e)
{
    if(Page.IsValid)
    {
        // update data store
    }
}

http://msdn.microsoft.com/en-us/library/system.web.ui.page.isvalid(v=vs.100).aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM