views:

1106

answers:

3

I'm trying to use a .Net FileUpload control along with a Regex Validator to limit filename to JPG, GIF, or PNG extensions. After postback, the filename is gone from the control (as expected), but this seems to cause the validator to fire and display its error text.

Can anyone suggest a fix, or a better way? Thank you!

A: 

Use a custom validator to do this check and call Page.IsValid in the method that handles the upload which will stop the processing of the upload if the file does not have the valid extension.

Rob West
+2  A: 

Just use a custom validator with the following javascript function:

function UploadFileCheck(source, arguments)
{
    var sFile = arguments.Value;
    arguments.IsValid = 
       ((sFile.endsWith('.jpg')) ||
        (sFile.endsWith('.jpeg')) ||
        (sFile.endsWith('.gif')) ||
        (sFile.endsWith('.png')));
}

The custom validator code:

<asp:CustomValidator ID="cvalAttachment" runat="server" ControlToValidate="upAttachment" SetFocusOnError="true" Text="*" ErrorMessage="Invalid: File Type (allowed types: jpg, jpeg, gif, png)" ClientValidationFunction="UploadFileCheck"></asp:CustomValidator>

That should be all your need to stop it client side before it gets posted back.

Kelsey
A: 

JavaScript has no "endsWith", so use this code for the custom validator:

function UploadFileCheck(source, arguments) { var sFile = arguments.Value; arguments.IsValid = ((sFile.match(/\.jpe?g$/i)) || (sFile.match(/\.gif$/i)) || (sFile.match(/\.bmp$/i)) || (sFile.match(/\.tif?f$/i)) || (sFile.match(/\.png$/i))); }

Phil P