0

For image upload , This is my code,

What is the error, its not checking in else part

if(!$('#upload').val())
                        {
                            alert('Upload Your Photo');
                            $('#upload').focus();
                            return false;
                        }
                        else{
                        $('input[type=file]').change(function () {
                        var val = $(this).val().toLowerCase();
                        var regex = new RegExp("(.*?)\.(jpg|jpeg|txt|png|docx|gif|doc|pdf|xml|bmp|ppt|xls)$");
                        if(!(regex.test(val)))
                         {
                        $(this).val('');
                        alert('Unsupported file');

                        }
                         }); 
                         }
3
Contributors
4
Replies
27
Views
2 Years
Discussion Span
Last Post by AntonyRayan
0

Hi,

maybe you have multiple file type fields in your page? Try by identifying the field by the ID attribute, for example:

// by default, submit is disabled
$("#submit").attr("disabled", "true");

$("#upload").on('change', function(){

    var val = $(this).val().toLowerCase();

    if(!val)
    {
        alert('upload your photo');
        $(this).focus();
        $("#submit").attr("disabled", "true");
        return false;
    }

    else
    {
        var regex = new RegExp("(.*?)\\.(jpg|jpeg|txt|png|docx|gif|doc|pdf|xml|bmp|ppt|xls)$");
        if (!(regex.test(val))) {
            $(this).val('');
            alert('Unsupported file');
        }

        $("#submit").removeAttr("disabled");
    }

});

Live example: http://jsfiddle.net/ms4grpxc/

By the way, you needed to escape correctly the backslash that starts the regular expression. If you add the id="submit" to the upload button you can disable the upload, but the above solution is not safe for two reasons:

  1. javascript can always be disabled, even if the upload is restricted to AJAX, an XHR can be emulated;
  2. a user can upload a double extension file: file.txt.php will not pass, but file.php.txt yes and if your server web, for example Apache, is not configured correctly, then it will execute the file like a PHP script.

Regarding this security issue read about the SetHandler vs AddHandler directives:

0

but I want to validate, when I select the image, not in submitting.

The code cereal provided does exactly that.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.