I'm using Fileinput Bootstrap for file input fields. Following is my code:-
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>
So, now I've an initial preview on one of my input field having id input-upload-img1 and no preview on the other input field.
Now I apply jQuery validation of the input field
img1: {
require_from_group: [1, '.file'],
accept: "image/*"
},
img2: {
require_from_group: [1, '.file'],
accept: "image/*"
}
But, when I submit the form, it still shows the error of saying Atleast 1 field is required. Why is it happening when I've already provided an image in the first input box? Also, If I browse separately again. it will work.
Why jQuery validation is showing error when initial preview field has already been provided.
Following is my dummy code:-
<!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>
As you can see, there's initially an image in the input field. But when I submit the form, it returns an error saying Please fill at least 1 of these field, since there's no file selected. How can I overcome this?
Here's the jsfiddle. But it somehow doesnt display the initial preview of the image, hence I recommend you to copy-paste this code and run it on your own system.
require_from_grouprule means. The rule says that at least one field must be completed. As soon as you select a file for upload, the rule is fully satisfied and the form is allowed to submit. Otherwise, I don't understand the issue as you're describing it.