2
$('#ad_pd_form').bootstrapValidator({ 
    fields: {     
        ad_pd_image: {
            validators: {
                file: {
                    extension: 'jpg,png',
                    type: 'image/jpg,image/png',
                    maxSize: 30(Height) * 30 (width), 
                    message: 'The selected file is not valid'
                       }
                          }
                      }
             }
    });

朋友们,我在 bootstrap 验证器中验证图像,我必须验证上传图像的高度和宽度,如何通过使用 bootstrap 验证器来实现这个概念。我只需要上传大小为 30 * 30 的图像。

4

1 回答 1

1

您需要为图片上传检查维度提供验证功能。

这是示例代码:

$(function () {
    $("#upload").bind("click", function () {
        //Get reference of FileUpload.
        var fileUpload = $("#fileUpload")[0];
 
        //Check whether the file is valid Image.
        var regex = new RegExp("([a-zA-Z0-9\s_\\.\-:])+(.jpg|.png|.gif)$");
        if (regex.test(fileUpload.value.toLowerCase())) {
            //Check whether HTML5 is supported.
            if (typeof (fileUpload.files) != "undefined") {
                //Initiate the FileReader object.
                var reader = new FileReader();
                //Read the contents of Image File.
                reader.readAsDataURL(fileUpload.files[0]);
                reader.onload = function (e) {
                    //Initiate the JavaScript Image object.
                    var image = new Image();
                    //Set the Base64 string return from FileReader as source.
                    image.src = e.target.result;
                    image.onload = function () {
                        //Determine the Height and Width.
                        var height = this.height;
                        var width = this.width;
                        if (height > 100 || width > 100) {
                            alert("Height and Width must not exceed 100px.");
                            return false;
                        }
                        alert("Uploaded image has valid Height and Width.");
                        return true;
                    };
                }
            } else {
                alert("This browser does not support HTML5.");
                return false;
            }
        } else {
            alert("Please select a valid Image file.");
            return false;
        }
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<input type="file" id="fileUpload" />
<input id="upload" type="button" value="Upload" />

于 2018-03-29T16:32:37.987 回答