jQuery Multiple File Upload Plugin check wheather empty or not - javascript

I have downloaded JQuery Multiple file uploader from this site
http://www.fyneworks.com/jquery/multiple-file-upload/
I need to check whether the file input field is null or not before submitting the form.
<form onsubmit="return validate();">
<input type="file" name="File" class="multi" />
<input type="file" name="File" class="multi" />
<input type="submit" name="BtnSubmit" value="save" />
</form>
I tried
function validate() {
$(".multi").each(function () {
var multi = $(this).val();
if (multi) {
return true;
} else {
return false;
}
});
}
Not working because the filed is always empty. So is there any other way to achieve this ?

try this
var multi = $(".multi").val();
if (multi) {
console.log("multi");
} else {
console.log("no multi");
}
fiddle:
http://jsfiddle.net/w4qVv/
UPDATE:
or you can do it like this
function validate(field) {
var fieldVal = $(field).val();
if(!fieldVal) alert("No files selected");
}
and then:
validate(".multi");
fiddle:
http://jsfiddle.net/jk8aZ/
UPDATE2:
yep, you can use each like this
var multi = (".multi");
$(multi).each(function () {
validate(this);
});
fiddle:
http://jsfiddle.net/jk8aZ/1/

Related

How to add remove class of div on input:file's onchange event?

<html>
<form class="form" id="helpForm" enctype='multipart/form-data' novalidate>
<div id="file_div" class="form-group">
<div class="controls">
<input type="file" id="file_upload" class="form-control square" accept="application/pdf" name="file_upload" onchange="return fileValidation()">
<div class="help-block" id="file_error"></div>
</div>
</div>
<button type="submit" class="btn btn-primary" id="form-submit">submit</button>
</form>
</html>
I have written some jquery code to work with it
function fileValidation() {
var fileInput = document.getElementById('file_upload');
var filePath = fileInput.value;
// Allowing file type
var allowedExtensions = /(\.pdf)$/i;
if(fileInput.files[0] == undefined) {
$('#file_div').removeClass('validate');
$("#file_div").addClass('error');
$('#file_error').css('display','block');
$('#file_error').append('<ul role="alert"><li>Pdf File is required field !</li></ul>');
return false;
} else if (!allowedExtensions.exec(filePath)) {
$('#file_div').removeClass('validate');
$("#file_div").addClass('error');
$('#file_error').css('display','block');
$('#file_error').append('<ul role="alert"><li>File type is not allowed !</li></ul>');
return false;
} else if (fileInput.files[0].size > 2097152) { //26214400 -25MB
$('#file_div').removeClass('validate');
$("#file_div").addClass('error');
$('#file_error').css('display','block');
$('#file_error').append('<ul role="alert"><li>File size must under 2MB !</li></ul>');
return false;
} else {
if (event == undefined) {
uploadFile();
}
return true;
}
}
if I do console.log() inside fileValidation() it print everything here.
but why my this code not doing its work?
$('#file_div').removeClass('validate');
$("#file_div").addClass('error');
$('#file_error').css('display','block');
$('#file_error').append('<ul role="alert"><li>Pdf File is required field !</li></ul>');
It work if I call fileValidation() on submit button.
Things to I am using for other validation. and inside this
(function(window, document, $) {
'use strict';
// Input, Select, Textarea validations except submit button
$("input,select,textarea,file").not("[type=submit]").jqBootstrapValidation({
filter: function () {
return $(this).is(":visible");
},
sniffHtml: false,
submitSuccess: function ($form, event) {
event.preventDefault();
fileValidation(); // this is working and doing all
}
});
})(window, document, jQuery);
Can anyone suggest , how I can achieve this on OnChange event?
Thanks
The issue here is $("input,select,textarea,file").not("[type=submit]").jqBootstrapValidation({}); function.
So if anyone help to find why it blocking that onchange function to work?

Regex always returning either always true or always false regardless of valid test value

I am trying to validate a form field using Regex. The field should contain 5 numbers (ie 12345 = valid, 1234a = invalid, 123456 = invalid), that is it. no more, no less. The problem is with different regex formats, the .test() method either always returns true, or always returns false. It never works for correct values and fails for incorrect values. All regex testers test the regex successfully for JavaScript but when I add it to my page (WordPress), I get these issues. I read up about the /g field should be removed and tried all that. still no luck.
HTML:
<form name="newform" action="Create.php" onsubmit="return validateForm()" method="POST" >
Code <br/><br/><input id="code" class="form-control" type="text" value="" name="code" onkeypress="CodeStyleRefresh()" />
<button type="submit" id="submit" name="submit">Create</button>
</form>
JavaScript:
<script type="text/javascript">
function validateForm(){
var CodePattern = new RegExp(/\b\d{5}\b/);
if(CodePattern.test(document.forms["newform"]["code"].value) == true)
{
return true;
}
else
{
return false;
}
}
function CodeStyleRefresh(){
document.getElementById("code").setAttribute("style", "background-color: #ffffff;");
}
</script>
Some other ways I have tried to specify the expression:
var CodePattern = new RegExp(/\b\d{5}\b/);
var CodePattern = new RegExp('/\b\d{5}\b/');
var CodePattern = /\b\d{5}\b/;
var CodePattern = '/\b\d{5}\b/';
var CodePattern = \b\d{5}\b;
var CodePattern = '\b\d{5}\b';
This is my first time ever touching regex and I am fairly new to the JavaScript family as well. Not having such a good time.
UPDATE:
I have gone back to basics. My JavaScript now looks as follows based on a few suggestions:
function validateForm(event)
{
console.log("Im running the script!");
console.log(event.target.querySelector("[name=code]").value);
var CodePattern = new RegExp(/\b\d{5}\b/);
var codeVal = event.target.querySelector("[name=code]").value;
if(CodePattern.test(codeVal) == true)
{
alert("Expression Passed!");
}
else
{
alert("Expression Failed!");
return false;
}
}
My HTML is now:
<form name="newform" onsubmit="return validateForm(event)" method="POST">
Code
<input id="code" class="form-control" type="text" value="" name="code" />
<button type="submit" id="submit" name="submit">Create</button>
</form>
Still this expression is only hitting the failed state and alerts expression failed.
If it helps, I am adding the JavaScript to a WordPress page, the form is normal html on the same page. I have tried adding the JavaScript to both the header and the footer but this does not change anything. I'm starting to think I should just check if the length of the field = 5 and if I can then cast it to an int instead of using RegEx at all!
Your regex is fine. If you are only getting the error when you upload your code to your wordpress site, I'd be tempted to say that your problem is your context, perhaps you have more than one form with the same name?
Try a context aware piece of code, update your html to:
<form name="newform" onsubmit="return validateForm(event)" method="POST">
Code
<input id="code" class="form-control" type="text" value="" name="code" onkeypress="CodeStyleRefresh()" />
<button type="submit" id="submit" name="submit">Create</button>
</form>
And your javascript:
function validateForm(event){
var myRegex = new RegExp(/\b\d{5}\b/);
//event.target holds the node element that triggered the function in our case, the Form itself
var myValue = event.target.querySelector("[name=code]").value; //here we find the input with the name=code inside the form that triggered the event
return myRegex.test(myValue) //return true if it passed, false if not
}
Since I cannot insert this much code in comments, I am posting an answer here to show how it all works.
function validateForm(frm, evt)
{
var codeVal = frm.code.value;
var CodePattern = /\b\d{5}\b/;
// comment below line after testing
evt.preventDefault();
if(CodePattern.test(codeVal) == true)
{
console.log("Expression Passed!");
return true;
}
else
{
console.log("Expression Failed!");
return false;
}
}
<form name="newform" onsubmit="return validateForm(this, event)" method="POST">
Code <br/><br/>
<input id="code" type="text" value="abc 12345 foo bar" name="code" />
<input type="submit" id="submit" name="submit" value="Create" />
</form>
Thank you for all the suggestions. I have learnt a few things by looking at them all and I have made a few changes.
I could not however get the regex to work properly in wordpress. I was forced to create a longwinded, dirtier solution to this. I will continue to look at possible solutions and test on other wordpress sites, but for now, this is the code I am using to validate the field:
function validateForm(frm, evt)
{
var codeVal = frm.code.value;
console.log("Code Value: " + String(codeVal));
// comment below line after testing
evt.preventDefault();
var lenPass = false;
var strlen = codeVal.length;
if(strlen == 5)
{
lenPass = true;
}
if(lenPass)
{
var c1 = Number.isNaN(Number(codeVal.charAt(0)));
var c2 = Number.isNaN(Number(codeVal.charAt(1)));
var c3 = Number.isNaN(Number(codeVal.charAt(2)));
var c4 = Number.isNaN(Number(codeVal.charAt(3)));
var c5 = Number.isNaN(Number(codeVal.charAt(4)));
console.log(c1);
console.log(c2);
console.log(c3);
console.log(c4);
console.log(c5);
var pass = true;
if(c1)
{
pass = false;
}
if(c2)
{
pass = false;
}
if(c3)
{
pass = false;
}
if(c4)
{
pass = false;
}
if(c5)
{
pass = false;
}
if(pass)
{
alert("Expression Stage 2 Passed!");
return true;
}
else
{
alert("Expression Stage 2 Failed!");
return false;
}
}
else
{
alert("Expression Stage 1 Failed!");
return false;
}
}
<html>
<head>
</head>
<body>
<form name="newform" onsubmit="return validateForm(this, event)" method="POST">
Code <br/><br/>
<input id="code" type="text" value="" name="code" />
<input type="submit" id="submit" name="submit" value="Create" />
</form>
</body>
</html>

How to send additional form fields using jquery file upload

I'm using jquery file upload to upload files to server side action. However, I would like to also send additional form fields as part of the form submit. Additionally, I want the formsubmit to happen only when the "submit" button is clicked.
Is this doable using jquery file upload?
I've created a jsbin: http://jsbin.com/mozujilede/1/edit?html,js,output
Desired behavior:
user should be alerted if they try to upload more files than allowed limit
additional form data should be sent to the server side along with multiple files
the form submit should happen only when user clicks submit button.
This is what I'm doing at the moment:
var maxFiles = 10;
$('#fileupload').fileupload({
singleFileUploads: false,
url: '/uploadUrl'
}).bind('fileuploadadd', function (e, data) {
var input = $('#input');
data.formData = {example: input.val()};
var fileCount = data.files.length;
if (fileCount > maxFiles) {
alert("The max number of files is "+maxFiles);
return false;
}
});
Try This
var byButton = false;
$("#sub-but").on("click",function(){
var inp = $("#files")[0];
if(inp.files.length > 10){
alert("Max number of files");
return false;
}
byButton = true;
$("#myForm").submit();
});
function validate(){
if(!byButton)
return false;
byButton = false;
return true;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm" onsubmit="return validate();">
<input type="text" placeholder="some extra items"/>
<input type="file" id="files" multiple="multiple"/>
<input type="button" value="Submit" id="sub-but"/>
</form>

Displaying range validator error message on html input

I have an input type =text in html and i have this js code in js file to show error message
var $form = $("#myid"),
$errorMsg = $("<span id='myerrormessagespan' class='error' style='color:red;'>*</span>");
var toReturn = 0;
$("input", $form).each(function () {
if ($(this).val() == "") {
if (!$(this).data("error")) {
$(this).data("error", $errorMsg.clone().insertAfter($(this)));
}
toReturn = 1;
}
else {
if ($(this).data("error")) {
$(this).data("error").remove();
$(this).removeData("error");
}
}
});
I am trying to convert this code to make range validator on input type=text field .dispalying only 5 digits in the textbox, but i couldn't achieve . Is there any easy way to do this ?
Thanks
Consider using the jQuery validation plugin instead, especially the rangelength method for your case. However, if you want to stick to the original code without using any library then I suggest you try the code below for example:
HTML:
<form id="myid" name="myid" method="post" action="/">name :
<input type="text" name="name" id="name" />age :
<input type="text" name="age" id="age" />
<input type="submit" id="submit" name="submit" value="Save" />
</form>
jQuery:
var $form = $("#myid"),
$errorMsg = $("<span id='myerrormessagespan' class='error' style='color:red;'>*</span>");
$("#submit").on("click", function () {
var toReturn = true;
$("input", $form).each(function () {
var value = $(this).val();
if((!$.trim(this.value).length) || (value.length > 5)) {
if (!$(this).data("error")) {
$(this).data("error", $errorMsg.clone().insertAfter($(this)));
}
toReturn = false;
}
else {
if ($(this).data("error")) {
$(this).data("error").remove();
$(this).removeData("error");
}
}
});
return toReturn;
});
Working JSFiddle Demo

Get value of upload fields and counting the array

I have the following html code :
<form name="uploadForm" action="" method="POST" enctype="multipart/form-data">
<input type="file" name="file_sub[]" />
<input type="file" name="file_sub[]" />
<input type="file" name="file_sub[]" />
<input type="file" name="file_sub[]" />
<input type="file" name="file_sub[]" />
<input type="button" onClick="javascript:submitform();" value="SUBMIT BTN" />
</form>
and here is the javascript function submitform() :
function submitform()
{
var minUpload = 1;
var uploadNo;
var count=document.uploadForm.file_sub.length;
for(a=0;a<count;a++)
{
if(document.uploadForm.file_sub.value != '')
{
uploadNo++;
}
}
if(uploadNo > minUpload){
document.uploadForm.submit();
}else{
alert('Please Upload Atleast ' + minUpload + ' files');
}
}
the javascript is suppose to validate and make sure atleast minUpload of the the file fields a file inside them.
but for some reason when I try to get the length of the file in the function I get an error (according to the debugger of chrome, I get "Uncaught TypeError: Cannot read property 'length' of undefined" ) however I have tried the same thing with checkboxes and it works just fine. What am I doing wrong? is it even possible to do such task in js?
You have to refer to file_sub[]. Fixed function:
var count = document.uploadForm["file_sub[]"].length;
function submitform(){
var minUpload = 1;
var uploadNo;
var files = document.forms['uploadForm']["file_sub[]"];
var count = files.length;
for(var a=0; a<count; a++){
if(files[a].value != ''){
uploadNo++;
}
}
if(uploadNo > minUpload){
document.forms['uploadForm'].submit();
} else {
alert('Please Upload Atleast ' + minUpload + ' files');
}
}

Categories

Resources