Thursday, January 3, 2013

javascript validation for file upload

Below is the article for adding javascript validation (or) jquery validation for a file upload that makes our life easier whether the file upload is a valid type or not.


if($('#upload_file').val() != '')
{
        var _validFileExtensions = [".jpg", ".jpeg", ".bmp", ".gif", ".png"]; // Can change the extensions if we need for doc type or something else
        if($('#upload_file').val() != '')
        {
            var sFileName = $('#upload_file').val();
            var blnValid = false;
            for (var j = 0; j < _validFileExtensions.length; j++)
            {
                var sCurExtension = _validFileExtensions[j];
                if (sFileName.substr(sFileName.length - sCurExtension.length, sCurExtension.length).toLowerCase() == sCurExtension.toLowerCase()) {
                    blnValid = true;
                    break;
                }
            }
            if(!blnValid)
            {
               alert("Sorry, " + sFileName + " is invalid, allowed extensions are: " + _validFileExtensions.join(", "));
                $('#upload_file').focus();
                return false;
            }
        }
 }

No comments: