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

                        }
                         }); 
                         }

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:

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

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

The code cereal provided does exactly that.

Okits working Thank u . But I needit while selecting image like onclick.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.