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!
-
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.
-
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.
-
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))); }
0 comments:
Post a Comment