jquery图像验证不适用于数组

时间:2017-01-09 08:55:56

标签: javascript jquery arrays jquery-validate

jQuery验证工作正常,但它不适用于数组。请在此处查看工作代码。

http://jsfiddle.net/rq5ra/1050/

如果我在输入中添加了数组,那么它就无法正常工作。

html代码

<form id="createprofile">
  <input type="file" name="profilepic[]">
  <input type="file" name="profilepic[]">
  <input type="submit" />
</form>

jQuery代码

$.validator.addMethod('filesize', function (value, element, param) {
    return this.optional(element) || (element.files[0].size <= param)
}, 'File size must be less than {0}');
jQuery(function ($) {
    "use strict";
    $('#createprofile').validate({
        errorElement: "label"
        , errorClass: "has-error"
        , submitHandler: function (form) {
            form.submit(); //return false;
        }
        , highlight: function (element) {
            $(element).closest('.form-group').removeClass('success').addClass('has-error');
        }
        , rules: {
            profilepic[]: { 
                extension: "jpg,jpeg"
                , filesize: 300000, //500kb
            } 
        },
        messages: {
            profilepic[]: { 
                extension: "Please upload only jpg, jpeg format"
                ,filesize: "Please upload maximum 500Kb"
            }
        }
    });
});

请帮我解决。

2 个答案:

答案 0 :(得分:0)

请添加&#34; profilepicp []&#34;

工作代码http://jsfiddle.net/rq5ra/1052/

int

答案 1 :(得分:-1)

html代码

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.js"></script>
<form id="FORM_SEND_IMAGE">
  <input type="file" id="file" />
  <input type="submit" value="submit" />
</form>

jquery代码

function getExtension(filename) {
    var parts = filename.split('.');
    return parts[parts.length - 1];
}

function isImage(filename) {
    var ext = getExtension(filename);
    switch (ext.toLowerCase()) {
    case 'jpg':
    case 'png':
    case 'gif':
        //etc
        return true;
    }
    return false;
}

$(document).on('submit', '#FORM_SEND_IMAGE', function(e) {

    e.preventDefault();
    e.stopPropagation();

    function failValidation(msg) {
        alert(msg); // just an alert for now but you can spice this up later
        return false;
    }

    var file = $('#file');
    if (!isImage(file.val())) {
        return failValidation('Please select a valid image');
    }

    var form_data = new FormData($(this)[0]);

    $.ajax({
        url: base_url + 'gallery/add',
        type: 'POST',
        data: form_data,
        dataType: 'json',
        beforeSend: function() {
            console.log('before');
        },
        error: function(error) {
            console.log(error);
        },
        success: function(data) {
            console.log(data);
        },
        complete: function() {
            console.log('complete');
        },
        processData: false,
        contentType: false
    });
});

demo jsfiddle