簡體   English   中英

文件輸入引導插件上的 Jquery 驗證

[英]Jquery validation on fileinput bootstrap plugin

我將Fileinput Bootstrap用於file輸入字段。 以下是我的代碼:-

HTML

<input id="input-upload-img1" type="file" class="file" data-preview-file-type="text" name="img1" accept='image/*,video/*'>
<input id="input-upload-img2" type="file" class="file" data-preview-file-type="text" name="img2" accept='image/*,video/*'>

Javascript

<script>
    $('#input-upload-img1').fileinput({
        initialPreview: [
            "<img src='img1' class='file-preview-image' alt='Desert'>",
        ]
    });
</script>

所以,現在我在一個具有 id input-upload-img1的輸入字段上進行了初始預覽,而在另一個輸入字段上沒有預覽。

現在我對輸入字段應用 jQuery 驗證

img1: {
    require_from_group: [1, '.file'],
    accept: "image/*"
},
img2: {
    require_from_group: [1, '.file'],
    accept: "image/*"
}

但是,當我提交表單時,它仍然顯示說Atleast 1 field is required的錯誤。 當我已經在第一個輸入框中提供了圖像時,為什么會發生這種情況? 另外,如果我再次單獨瀏覽。 它會起作用的。

為什么已經提供初始預覽字段時 jQuery 驗證顯示錯誤。

以下是我的虛擬代碼:-

<!DOCTYPE>
<html>
<head>
    <style type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-fileinput/4.3.1/css/fileinput.min.css"></style>
</head>
<body>
    <form>
        <input id="input-upload-img1" type="file" class="file" data-preview-file-type="text" name="img1" accept='image/*'>
        <button type="submit">Submit</button>
    </form>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/jquery.validation/1.15.0/jquery.validate.min.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/jquery.validation/1.15.0/additional-methods.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-fileinput/4.3.1/js/fileinput.min.js"></script>
<script type="text/javascript">
    $("#input-upload-img1").fileinput({
        initialPreview: [
            "<img src='http://www.gettyimages.pt/gi-resources/images/Homepage/Hero/PT/PT_hero_42_153645159.jpg' class='file-preview-image' width=20% height=20%>"
        ]
    });

    $('form').validate({
        rules: {
            img1: {
                require_from_group: [1, '.file'],
                accept: "image/*,video/*",
                filesize: 100000000
            }
        }
    })

</script>
</html>

如您所見,輸入字段中最初有一個圖像。 但是當我提交表單時,它返回一個錯誤,說Please fill at least 1 of these field ,因為沒有選擇文件。 我該如何克服呢?

這是jsfiddle 但它不知何故不顯示圖像的初始預覽,因此我建議您復制粘貼此代碼並在您自己的系統上運行它。

我將 Fileinput Bootstrap 用於文件輸入字段。

我懷疑原始input元素是隱藏的,因此通常會觸發驗證的各種用戶事件不會發生。 我不熟悉Fileinput插件,因此您可能需要執行以下一項或兩項操作:

  1. 確保您將ignore選項設置為[] 這將確保無論如何都會驗證隱藏的輸入元素。

  2. 當您與Fileinput元素交互時,您需要以編程方式觸發驗證。 如果這個插件提供了一個回調函數,只要選擇一個文件就會觸發,把$('[name="img1"], [name="img2"]').valid(); 在這個函數里面。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM