简体   繁体   中英

JQuery Validate Image Upload File Type

I have a JQuery script that validates the upload of avatar images but I need it to prevent the upload of anything other than PNG, JPG & GIF images. Any way of implementing this into the code I have? Here is the code:

$('#addButton').click(function () {
    var avatar = $("#avatarupload").val();
    if(avatar.length < 1) {
        avatarok = 0;
    }
    //ELSE IF FILE TYPE
    else {
        avatarok = 1;
    }
    if(avatarok == 1) {
        $('.formValidation').addClass("sending");
        $("#form").submit();
    }
    else {
        $('.formValidation').addClass("validationError");
    }
    return false;
});

This should check the file extension

var extension = avatar.split('.').pop().toUpperCase();
if (extension!="PNG" && extension!="JPG" && extension!="GIF" && extension!="JPEG"){
    avatarok = 0;
}

So the full code should looks like

$('#addButton').click(function () {
    var avatar = $("#avatarupload").val();
    var extension = avatar.split('.').pop().toUpperCase();
    if(avatar.length < 1) {
        avatarok = 0;
    }
    else if (extension!="PNG" && extension!="JPG" && extension!="GIF" && extension!="JPEG"){
        avatarok = 0;
        alert("invalid extension "+extension);
    }
    else {
        avatarok = 1;
    }
    if(avatarok == 1) {
        $('.formValidation').addClass("sending");
        $("#form").submit();
    }
    else {
        $('.formValidation').addClass("validationError");
    }
    return false;
});

You can try for jquery validate for validation which is having accept :

vCategoryImage:{
   accept: "image/*"
}

As per your requirement the purpose is upload avatar ,so you can check with drop zone open source file upload extension Drop Zone .

Or else you can check with the various plugins available from Jquery.

For Example plugin please check the below links

Hope this will be helpful.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM