Nida
Nida

Reputation: 1702

PDF Validation issue

I have used regular expression validation like below

<asp:RegularExpressionValidator ID="FileValidationPDF" runat="server" ControlToValidate="OFile"
ErrorMessage="Only PDF Allowed" ValidationExpression="([a-zA-Z0-9\s_\\.\-:])+(.pdf)$"></asp:RegularExpressionValidator>

It is not accepting files with name like MED1001855 (4).pdf or W-9Info+(1).pdf.

Please help !!!

Upvotes: 0

Views: 576

Answers (1)

VDWWD
VDWWD

Reputation: 35524

You can do a 3 step validation. First add accept=".pdf" tot the FileUpload Control. That will only show pdf files on the client pc. Read more.

<asp:FileUpload ID="OFile" runat="server" accept=".pdf" />

Then the RegularExpressionValidator, since users could stil select All files in the above step and still select a different file type.

<asp:RegularExpressionValidator ValidationExpression="^.*\.(pdf|PDF)$" ID="FileValidationPDF" runat="server" ControlToValidate="OFile" ErrorMessage="Only PDF Allowed"></asp:RegularExpressionValidator>

And last always do server side validation

protected void Button1_Click(object sender, EventArgs e)
{
    if (OFile.HasFile)
    {
        if (OFile.PostedFile.ContentType == "application/pdf")
        {
            //file is a PDF
        }
    }
}

Upvotes: 1

Related Questions