2

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!

4 Answers 4

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

You can set the IsValid property of RegularExpression validator instead if using custom validator. Check out my answer. Thanks.
0

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.

Comments

0

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))); }

Comments

0

Using custom validator is way too long. Instead you can simply set the IsValid property of the RegularExpression in the click event of your upload button.

http://blogs.cametoofar.com/post/aspnet-regular-expression-validator-firing-after-postback.aspx

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.