5 file fields, 1 validation for all - javascript

I have 5 file inputs that I perform a file validation using the following code:
$("#fileinput").change(function() {
var file = this.files[0];
var fileType = file.type;
var match = ['application/pdf', 'image/jpeg', 'image/png', 'image/jpg'];
if(!((fileType == match[0]) || (fileType == match[1]) || (fileType == match[2]) || (fileType == match[3]) || (fileType == match[4]) || (fileType == match[5]))){
Swal.fire("Erro: Invalid file format!", "Only: PDF, JPG, JPEG e PNG", "error");
$("#docpessoal").val(null);
$(".custom-file-label").text('Selecionar documento...');
return false;
}
});
Instead of repeating the function for each file input I would like to to use the same function but changing the selector ID based on which input the user clicked. (I'm not sure if it's possible)
Heres the code that I tried to do that:
var nomeInput = '_';
$('input[type="file"]').click(function(){
var nomeInput = $(this).attr('id');
});
I tried to use the variable nomeInput in the .change selector but it doesn't work.
Is there anyway to achieve that?

Delegate the change event to the form, in the handler, get a reference to the changed input via the event object, you don't need any messy identifiers or DOM traversing in the handler function. Like this:
$('.validate-form').on('change', '[type="file"]', e => {
const type = e.target.files[0].type;
if (!/application\/pdf|image\/jpe?g|image\/png/.test(type)) {
console.log('Filetype doesn\'t match.');
} else {
console.log('Accepted filetype.')
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="validate-form">
<input name="dummy">
<br>
<input type="file" name="file[]">
<input type="file" name="file[]">
<input type="file" name="file[]">
<input type="file" name="file[]">
<input type="file" name="file[]">
</form>
If the form contains file inputs you don't want to validate, group the wanted inputs with a class, and attach the listener using that class instead of more general attribute selector.

Related

How to not open File upload when parameters are not meet javascript

How to not open the file upload box when input mytextField is null.
<input type="text" id="mytextField">
<input type="file" multiple id="myFileUpload">
<script>
document.getElementById("myFileUpload").addEventListener("click", function () {
var myTextF = document.getElementById("mytextField");
if(myTextF = null || myTextF == ''){
//will not open the file upload
} else {
//let the file upload open
}
});
</script>
You can disable the upload button when textarea is empty and enable it when textarea contains text.
<input type="text" onkeyup="checkField()" id="mytextField">
<input type="file" multiple id="myFileUpload" disabled="disabled">
script:
function checkField(){
var myTextF = document.getElementById("mytextField");
if(myTextF.value.trim() != ""){
document.getElementById("myFileUpload").disabled = false;
}
}
Used the trim() function to prevent empty whitespace texts.
Here you are assigning myTextF to the element, rather than the innerText.
Try with var myTextF = document.getElementById("myTextF").innerText;
If something doesn't work, you could always try to log the output to the console.
In this case, because you are assigning the element, that resolves as TRUE, and it will always try to open the file.
document.getElementById("myFileUpload").addEventListener("click", function () {
var myTextF = document.getElementById("mytextField");
if(myTextF = null || myTextF == ''){
//will not open the file upload
console.log("I should not open file")
} else {
//let the file upload open
console.log("I should open the file")
}
});
" I should open the file"

how to prevent input type file from accepting some inputs on change function

I'm working on a project and I need the user to upload only pdf files.
I'm trying to do this in the front-end so whenever the input detects a file type that is not a pdf should reject it. Everything seems correct. However, when I hover over the input it shows me that the wrong file is uploaded. So what should I do?
function changeName(elem) {
$("input[type='file']").
elem.on("change", function() {
var fileName = elem.val().split("\\").pop();
var fileExtension = elem.val().split(".").pop();
if (fileExtension === "pdf") {
elem.siblings(".Syllabus").text(fileName);
} else {
elem.siblings(".Syllabus").val('');
elem.siblings(".Syllabus").text('...');
alert('Only PDF files are accepted');
}
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label class="Syllabus fileReset">...</label>
<input type="file" accept="application/pdf" name="file1" onClick="changeName($(this));" required class="upload-button removable" />
This code works better than what you posted
$("input[type='file']").on("change", function(e) {
var elem = $(this);
elem.siblings(".Syllabus").text("...")
var fileName = elem.val().split("\\").pop();
var fileExtension = elem.val().split(".").pop();
if (fileExtension !== "pdf") {
elem.siblings(".Syllabus").text('Only PDF files are accepted')
elem.replaceWith(elem.val('').clone(true));
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label class="Syllabus fileReset">...</label>
<input type="file" accept="application/pdf" name="file1" required class="upload-button removable" />

Validate on select while choosing files for upload

I am trying to validate file types as soon as the files are choosen for upload
Below is my html code
<label> <input type="file" id="image" name="upload[]" multiple="multiple" onclick="validateFileExtension()" />
Validation code
function validateFileExtension() {
var ext = $('#my-file-selector').val().split('.').pop().toLowerCase();
if($.inArray(ext, ['gif','png','jpg','jpeg', 'pdf']) == -1) {
alert('invalid extension!');
}
}
But it is not validating as soon as the files are selected. Only upon submitting the form, the validation happens. i have other a jquery for validation on submit. I need to validate on select. Please help out
onclick is not firing after you select a file. using onchange instead works.
function validateFileExtension(element) {
var files = $(element)[0].files;
for(var i = 0; i < files.length; i++) {
var ext = files[i].name.split('.').pop().toLowerCase();
if ($.inArray(ext, ['gif', 'png', 'jpg', 'jpeg', 'pdf']) == -1) {
console.log('invalid extension!', ext);
} else {
console.log('valid extension :)', ext);
}
}
}
function validateForm(form) {
validateFileExtension(form.image);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="file" id="image" name="upload[]" multiple="multiple" onchange="validateFileExtension(this)" />
<br>
<input type="submit" onclick="validateForm(this.parentNode)" />
</form>
You need to use onchange and need to loop through the files array if using the multiple attribute
function validateFileExtension(element) {
var i;
for (i = 0; i < element.files.length; i++) {
// make sure in all browsers were just looking at the file name
var ext = element.files[i].name.split('.')[1].toLowerCase();
if ($.inArray(ext, ['gif', 'png', 'jpg', 'jpeg', 'pdf']) == -1) {
element.value = ""; // clear the input field
alert('invalid extension!'); // now alert user
}
}
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>File</label>
<input type="file" id="image" name="upload[]" multiple="multiple" onchange="validateFileExtension(this);" />

$('element').click() not working

This is my file input element:
<input type="file" id="StudentPhoto" value="StudentPhoto" style="display: none;">
This is the validation function:
$(document).ready(function() {
$('#StudentPhoto').change(function()
{
var file_data = $("#StudentPhoto").prop("files")[0];
var size = file_data.size;
var type = file_data.type;
var name = file_data.name;
var input = $("#StudentPhoto");
if(type !== 'image/png' && type !== 'image/jpg' && type !== 'image/jpeg')
{
alert("Only JPG & PNG files are allowed to upload as student photo.");
$('#StudentPhoto').click();
}
else if(size > 2097152)
{
alert("The maximum photo size is 2MB\n");
$('#StudentPhoto').click();
}
});
});
If the file chosen by the user has an invalid format or size, it's supposed to pop up the dialog to ask him to choose the file again, but it doesn't, the statement $('#StudentPhoto').click(); in the function doesn't work. Why? Is there any other method?
Or you can use the .trigger() method to make the click event fire on the button. We'll also use input since you stored the file field already.
input.trigger('click');
Hope this helps.
You can use HTML DOM click() method:
document.getElementById('StudentPhoto').click();
Change your file input element to:
<input type="file" id="StudentPhoto" value="StudentPhoto" style="visibility: hidden">
Note that I used visibility: hidden, instead of display: none.
You cannot call the click event on a non-displayed file input.
you need to insert your callback withing the click event:
$(document).ready(function()
{
$('#StudentPhoto').change(function()
{
var file_data = $("#StudentPhoto").prop("files")[0];
var size = file_data.size;
var type = file_data.type;
var name = file_data.name;
var input = $("#StudentPhoto");
if(type !== 'image/png' && type !== 'image/jpg' && type !== 'image/jpeg')
{
alert("Only JPG & PNG files are allowed to upload as student photo.");
$('#StudentPhoto').click();
}
else if(size > 2097152)
{
$('#StudentPhoto').click(function(){
alert("The maximum photo size is 2MB\n");
});
}
});
});

Javascript validate filename before upload

I simply want to validate the filename of the image being uploaded to ensure that it does not have spaces or unusual characters.
This is my latest attempt from searching around, still no luck. Could it be something to do with the path of the file? is it taking this or just the file name into account?
I have this and a check of the extention working server side with php, but I would like a prompt to the user before submitting.
At this point in time im getting the alert pop up even whether i use a file name it should accept or one that it should reject.
JavaScript
function validate(elem){
var alphaExp = /^[a-zA-Z_-]+$/;
if(elem.value.match(alphaExp)){
return true;
}else{
alert("File name not suitable");
elem.focus();
return false;
}
}
HTML
<label for="file">Filename:</label>
<input type="file" name="filename" id="filename" onchange="validate(this)" />
<p><input type="submit" name="submit" class="submit" value="Submit" />
</form>
You will need to use a much more complex regular expression for this, because the elem.value you are checking won't be something like image123.jpg but more something like C:\fakepath\randomfolder\some other folder\image123.jpg
You might want to check into this : http://www.codeproject.com/Tips/216238/Regular-Expression-to-validate-file-path-and-exten
The exemple you'll find on this page is mostly for documents, not images, but you can twist it a bit to fit your needs like this :
^(?:[\w]\:|\\)(\\[a-z_\-\s0-9\.]+)+\.(png|gif|jpg|jpeg)$
you can use this function too....
<script type="text/javascript">
function getNameFromPath(strFilepath) {
var objRE = new RegExp(/([^\/\\]+)$/);
var strName = objRE.exec(strFilepath);
if (strName == null) {
return null;
}
else {
return strName[0];
}
}
</script>
and
<script language="javascript">
function Checkfiles() {
var fup = document.getElementById('filename');
var fileName = fup.value;
var ext = fileName.substring(fileName.lastIndexOf('.') + 1);
if(ext == "gif" || ext == "GIF" || ext == "JPEG" || ext == "jpeg" || ext == "jpg" || ext == "JPG" || ext == "doc") {
return true;
} else {
alert("Upload Gif or Jpg images only");
fup.focus();
return false;
}
}
</script>
it is very very simple with test function
function validate(form){
if (/\s/.test(form.elements.file.value)) {
alert(' filename contains spaces. Please rename the file.');
return false;
}
return true;
}
<html>
<body>
<form onsubmit="return validate(this);">
<input type="file" name="file" value="" >
<input type="Submit" value="Submit" >
</form>
</body>
</html>
Source https://codehurdles.blogspot.in/2017/11/javascript-validate-filename-before.html

Categories

Resources