I have a FileUpload control to upload a certificate file. The user has to upload the file the first time, in subsequent visits to the page, we display the certificate content on the page, so it's not necessary to upload a file again.
Now I want to validate that a certificate is uploaded at least at once. The rest of the page uses ASP.NET validation controls so I want to go ahead with the same.
I can't use a RequiredFieldValidator on the FileUpload, because then it will fire everytime I try to save the page, which is wrong.
I tried using a CustomValidator and used the serverside validation, but seems that too fires only if I click on the file uploader. If I just leave it alone, the server side validation is not triggered.
I can of course do the validation on the [Save] button click event, but is there a proper way to do that using the validator events themselves?
CustomValidator:
<asp:CustomValidator ID="cusCertifacteExistanceValidator" runat="server" ValidationGroup="ConfigValidation" CssClass="errorMsg" ControlToValidate="fcertificate" Enabled="false" ErrorMessage="Certificate is not available" OnServerValidate="ValidateCertificateUpload">*</asp:CustomValidator>
CustomValidator Server side validation:
protected void ValidateCertificateUpload(object source, ServerValidateEventArgs args)
{
args.IsValid = false;
var existingCertificate = string.Empty;
if (ViewState["loginProviderProperties"] != null)
{
existingCertificate = ((List<Configuration>)ViewState["properties"]).Find(p => p.Name == "certificate").Value;
}
if (fX509Certificate.HasFile || existingCertificate != string.Empty)
{
args.IsValid = true;
}
}