JQuery Validate Image Upload File Type

2019-06-04 23:30发布

问题:

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

回答1:

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


回答2:

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

vCategoryImage:{
   accept: "image/*"
}