Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Web-forms custom validator not firing

I have a custom validator on my page for a file upload control.

<asp:FileUpload ID="fuVendorBrief" runat="server" />
<br />
<asp:CustomValidator ID="cvVendorBriefFile" Display="Dynamic" runat="server" ValidationGroup="EditorValidate" ControlToValidate="fuVendorBrief" OnServerValidate="cvVendorBriefFile_ServerValidate" ErrorMessage="You must upload a vendor brief PDF file.">     
</asp:CustomValidator>

I then also have a button.

<asp:Button ID="btnSubmit" ValidationGroup="EditorValidate" OnClick="btnSubmit_Click" runat="server" Text="Add Vendor Brief" />

I have defined my custom validator event like so...

protected void cvVendorBriefFile_ServerValidate(object source, ServerValidateEventArgs args)
{
    CustomValidator fileUploadValidator = (CustomValidator)source;
    FileUpload vendorBriefFileUpload = (FileUpload)fileUploadValidator.Parent.FindControl(fileUploadValidator.ControlToValidate);
    args.IsValid = vendorBriefFileUpload.HasFile && vendorBriefFileUpload.FileName.ToLower().EndsWith(".pdf");
}

This custom validator isn't even getting fired. Everything looks alright to me. If I drop a breakpoint anywhere in the server validation event it does not get hit when I click submit. I can hit breakpoints in the submit button's click event however.

Any ideas?

EDIT - I have other validation controls, like required field validators, on the page and they fire just fine.

EDIT 2 - If you want the full source of the page and its codebehind then follow these links:

  • ASPX
  • CS
like image 737
Chev Avatar asked Apr 15 '11 19:04

Chev


1 Answers

Try removing ControlToValidate entirely. Though I've never tried to validate a file upload before, most validators won't fire (except RequiredField) if the contents are empty. Taking off the control to validate should make it fire always for that group.

EDIT (Chevex) - The ControlToValidate was the issue, but not because it was broken. By default it will not fire on controls with no value, as stated above. Setting the custom validator control property ValidateEmptyText="true" solves the issue. Sad that I had to start this giant question just to find that, but now we know! :)

like image 131
Jamie Treworgy Avatar answered Oct 16 '22 09:10

Jamie Treworgy