Only specific file show ( eg PDF) before uploading in javascript - javascript

I have a scenario where I am only allowed to upload specific file types, e.g. PDF.
I don't want to validate the type at form submit time. I need to verify the type is OK before selecting the file. Keep in mind the accept attribute is not supported in HTML5.
I have two options in mind.
Only acceptable file types should be available choices.
If possible, trigger a Javascript function after selecting a file. Opposite of onclick.
This is how I tried to validate on submit:
<form name="fileupload" onsubmit="return file_upload();">
<table align="center" bgcolor="#8080FF" height="100">
<tr>
<th> Fileupload:</th>
<td> <input type="file" name="word" id="word" > </td>
</tr>
<tr>
<td> <input type="submit" /> </td>
</tr>
</table>
</form>
<script type="text/javascript">
function file_upload()
{
var imgpath = document.getElementById('word').value;
if (imgpath == "") {
alert("upload your word file");
document.file.word.focus();
return false;
}
else {
// code to get File Extension..
var arr1 = new Array;
arr1 = imgpath.split("\\");
var len = arr1.length;
var img1 = arr1[len - 1];
var filext = img1.substring(img1.lastIndexOf(".") + 1);
// Checking Extension
if (filext == "doc" || filext == "docx") {
alert("File has been upload correctly")
return true;
}
else {
alert("Invalid File Format Selected");
document.form.word.focus();
return false;
}
}
}
</script>

Related

How to get value of dynamically generated textbox with same id using AJAX/PHP?

In this webpage I am generating multiple textbox dynamically and each textbox is meant to hold unique value and I want to get that value dynamically.But I'm not being able to catch the value of the textbox according to its position. This code is only working for the firstly generated textbox. I have code like this
<tr>
<td align="center"><input type="text" name="serialNoArray[]" id="serialArray" onChange="checkusername()" ><span id="std_id_status"></span></td>
</tr>
<script>
function checkusername() {
var s = _("serialArray").value;
if(s != "") {
_("std_id_status").innerHTML = 'checking ...';
var ajax = ajaxObj("POST", "sellingDetails.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true){
_("std_id_status").innerHTML = ajax.responseText;
}
}
ajax.send("std_id_check="+s);
}
}
</script>
First you should use classes not id, because an element with id must be unique for the entire document.
And since you use onChange you can pass the element using this like that onChange="checkusername(this)" .
I guess you should also change the code of the restrict function onkeyup="restrict('serialArray')" also but i do not see that code so I cannot help you more if you do not provide this code too...
<tr>
<td align="center"><input type="text" name="serialNoArray[]" class="serialArray" onkeyup="restrict('serialArray')" onChange="checkusername(this)" ><span class="std_id_status"></span></td>
</tr>
Then you can get only the value of the element being changed and change the html of the matching span only.(I use jQuery in the example so you should include it in your document.)
<script>
function checkusername(s) {
if (s.value != "") {
$(s).nextAll('.std_id_status').first().html('checking ...');
var ajax = ajaxObj("POST", "sellingDetails.php");
ajax.onreadystatechange = function() {
if (ajaxReturn(ajax) == true) {
$(s).nextAll('.std_id_status').first().html(ajax.responseText);
}
}
ajax.send("std_id_check=" + s.value);
}
}
</script>
Since i do not have all your javascript code I could not test it but something like this should work.
I have not tested but this should do it
All the dynamically generated textboxes, give them a class
<input type="text" class="tagMe" placeholder="Enter Serial No." onkeypress="return isNumberKey2(event)" onkeyup="restrict('serialArray')" onChange="checkusername()" required autofocus >
Collecting the data
var info= "";
$('.tagMe').each( obj, function( key, value ) {
if(info != "")
info += "^"; // ^ is a delimiter
info += value;
});
Send info to your server, split on ^ and parse data (careful of empty elements)

File type validation!! for generated input file tag elements

JSP:
----
<div ID="items">
input id="file5" type="file" path="files" name="files" size="40" /> Other documents
</div>
Javascript:
-----------
<script type="text/javascript">
var items=1;
function AddItem() {
var div=document.getElementById("items");
var button=document.getElementById("add");
items++;
newitem="";
newitem+="<input type=\"file\" path=\"files\" name=\"files\"";// + items;
newitem+="\"id=file"+items;
newitem+="\" size=\"40\"> Other documents";
newitem+=" <input type=\"button\" class=\"button\" id=\"delButton"+items;
newitem+="\" value=\"\" name=\"button"+items;
newitem+="\" onclick=deletethisRow("+items+")>";
newnode=document.createElement("div");
newnode.setAttribute("id","child"+items);
newnode.innerHTML=newitem;
div.insertBefore(newnode,button);
}
function deletethisRow(obj){
var fileElement=document.getElementById("file"+obj);
var buttonElement=document.getElementById("delButton"+obj);
var childDivName="child"+obj;
if (buttonElement) {
var child = document.getElementById(childDivName);
var parent = document.getElementById("items");
parent.removeChild(child);
}
}
</script>
---
Above is the JSP code as well as JavaScript snippets.. I'm trying to validate the input files....
I want to allow only jpg,png,pdf,doc,docx file types to be upload??
Any thoughts on how to achieve this?
Thanks and regards,
Satish Krishnamurthy
You can change your input tag:
<input type="file" name="pic" id="pic" accept=".someext, image/gif, image/jpeg" />
But please don't rely on client-side validation. Check it server-side or people can disable the client-side checks and upload even executable scripts.
function Checkfilesextension()
{
var fileToupload = document.getElementById('elementId');
var fileName = fileToupload .value;
var ext = fileName.substring(fileName.lastIndexOf('.') + 1);
ext.toLowerCase
if(ext =="GIF" || other extension) // add other extensions
{
return true;
}
else
{
alert("Upload only the allowed files");
return false;
}
}
This would check for the extension of the files....have not tested the code though

passing a javascript validation to dynamic textboxes in mvc3

Hello everyone i am working on a project similar to a shopping cart.I am using the below code to generate textboxes(for selecting the quantity) in my view:
#foreach (var item in Model)
{
<tr>
<td align="left" class="Text_nocolor">
#Html.DisplayFor(modelItem=>item.ProductName)
/td>
<td align="right" class="Text_nocolor" valign="top">
#using (Html.BeginForm("Update", "Cart", new { UserID = Request.QueryString["UserID"] }, FormMethod.Post, new { id = "myForm" }))
{
<input id="Quantity" type="text" class="Text_nocolor" name="Quantity" value="#item.Quantity" #*onblur="return NumberOnlyTextBox(event)"*# onchange="return allownumbers()" maxlength="3"/>
#Html.Hidden("unitrate", item.Rate)
<input type="submit" value="Edit" class="Text_nocolor" onkeypress="return validateNumbersOnly(e);" onclick="return RegainFocus();" />
}
In the above code "id=Quantity" represents the textboxes.
and i have written a javascript for numbers only validation for these textboxes.
These are my javascript functions:
<script type="text/javascript">
function RegainFocus() {
if ((document.getElementById("Quantity").value).length == 0) {
document.getElementById("Quantity").focus();
alert("Quantity cannot be empty");
document.getElementById("Quantity").value = document.getElementById("Quantity").defaultValue;
return false;
}
else if ((document.getElementById("Quantity").value) > 100) {
alert("There is no enough inventory for this product to fulfill your order");
document.getElementById("Quantity").value = document.getElementById("Quantity").defaultValue;
return false;
}
}
</script>
<script type="text/javascript">
function allownumbers() {
// var elements = document.getElementsByName('Quantity');
// for()
var val = parseInt(document.getElementsByName("Quantity").item(1).value);
alert(val);
if (!val || val < 1) {
alert('Please enter a valid value');
document.getElementById("Quantity").value = document.getElementById("Quantity").defaultValue;
return false;
}
document.getElementById("Quantity").value = val;
return true;
}
</script>
My problem is that the validation works only for the first textbox not the others.
Can anyone pls provide a solution? Thank you
Try it using the following code snippet:
onkeypress="return validateNumbersOnly(this);" onclick="return RegainFocus(this);"
...
function RegainFocus(obj)
{
if ((document.getElementById(obj).value).length == 0) {
..
}
..
Hope it helps.

html form javascript gets ignored

I am having difficulties to implement JavaScript into my html form.
I am using alot of PHP throughout. The code I am about to post, is included in a seperate page the user accesses. It is a php page.
The form currently does not include action=, which would submit it to formposts.php. I took it out to see if my JavaScript just got ignored and the form was sent before checkign JavaScript. But even without action, my form does not respond to the JavaScript.
I have used simple forms of JS, just to check if it works, before getting down to details. I really need some help pls on how to make this work, I dont know where the problem is !!
I have included the script call when opening the form, and when closing. onsubmit // onclick I have also tried including a label to show text. The JS is at the end off the code. You can ignore some of the text / script. I guess the opening of the form, first three input types, the closing of the form and JS is included. I have taken some out, as it is a long form.
<p><?php echo $session->getText("profileInfo",$language); ?></p>
<table width="530" border="0">
<tr>
<th scope="col" width="40%"><form enctype="multipart/form-data" method="POST" onsubmit="return checkForm()" name="registration">
<img src="<?php echo $userDetails['picUrl']; ?>" border="none"> ;</th>
<th scope="col" width="60%"><h3><?php echo $session->getText("profileMenuPersonal",$language); ?></h3></th>
</tr>
<tr>
<td><h4><?php echo $session->getText("regPic",$language); ?></h4></td>
<td><input type="file" name="uploaded" id="uploaded" onblur="checkType()" /> <label id="picMSG"></label> </td>
</tr>
<tr>
<td><h4><?php echo $session->getText("regFname",$language); ?></h4></td>
<td><input type="text" id="firstName" name="firstName" value="<?php echo $userDetails['firstName']; ?>" /></td>
</tr>
<tr>
<td><h4><?php echo $session->getText("regLname",$language); ?></h4></td>
<td><input type="text" id="lastName" name="lastName" value="<?php echo $userDetails['lastName']; ?>" /></td>
</tr>
<tr> <!-- I have taken some code out for readability of this post -->
<td><input type="hidden" id="reqtype" name="reqtype" value="personalDetails" />
<input type="hidden" id="realUserId" name="realUserId" value="<?php echo $realUserId; ?>" /></td>
<td><input type="submit" name="submit" value="update / save" class="button" onclick="return checkForm()" />
</form>
</td>
</tr>
</table>
<script type="text/javascript">
function checkForm()
{
var picture = document.getElementById('uploaded').value;
var firstName = document.getElementById('firstName').value;
var lastName = document.getElementById('lastName').value;
var email = document.getElementById('email').value;
var address1 = document.getElementById('address1').value;
var address2 = document.getElementById('address2').value;
var postCode = document.getElementById('postCode').value;
var email = document.getElementById('email').value;
// files types that r not allowed
// And are considered harming -
// someone purposfully trying to harm the system
var str1 = ".php";
var str2 = ".js";
var str3 = ".html";
if(!document.registration.firstName.value)
{
alert('please enter name');
return false;
}
if(picture.indexOf(str1) != -1 || picture.indexOf(str2) != -1 || picture.indexOf(str3) != -1)
{
alert("You have tried to upload content that may harm our system. The admin has been contacted and your account flagged. You may be deleted.");
return false;
}
// allowed file types
var str1 = ".jpeg";
var str2 = ".gif";
var str3 = ".png";
if(picture.indexOf(str1) != -1 || picture.indexOf(str1) != -1 || picture.indexOf(str1) != -1 )
{
return true;
}else{
alert("We only allow jpeg, gif and png files to be uploaded.");
return false;
}
}
function checkType()
{
var picture = document.getElementById('uploaded').value;
var element = document.getElementById('picMSG').value
// files types that r not allowed
// And are considered harming -
// someone purposfully trying to harm the system
var str1 = ".php";
var str2 = ".js";
var str3 = ".html";
if(picture.indexOf(str1) != -1 || picture.indexOf(str2) != -1 || picture.indexOf(str3) != -1)
{
element.innerHTML = "invalid type";
element.style.color = "red";
}
// allowed file types
var str1 = ".jpeg";
var str2 = ".gif";
var str3 = ".png";
if(picture.indexOf(str1) != -1 || picture.indexOf(str1) != -1 || picture.indexOf(str1) != -1 )
{
return true;
}else{
}
}
</script>
Does anyone have an idea why my "simple" JS is being ignored ??
I am new to PHP and JS. but wiould have thought this was a simple task. What am I doing worng ?
this is my wild guess... after i stripped your code to bits... http://jsfiddle.net/VVYR3/15/
change your submit button to:
onclick="checkForm()" instead of onsubmit="return checkForm()" (you can experiment further once you get this bit working)
and most importantly your script shouldn't be AFTER your form, instead place it in <HEAD>
It's kind of hard to debug it for you since you removed part of the code but I tried anyway and checkForm was called on submit allright. It fails on
var email = document.getElementById('email').value;
since there is no element with the id of "email" on which to find a value.
Your validation is somewhat sloppy though, what about a file called jpg.exe. It would pass as the code is now.
Have you considered not reinventing the wheel and use a tested framework instead? There are plenty of them out there, and they even have nice fancy ajax functionality. Like this: http://valums.com/ajax-upload/
i assume that you have to do this
<input type="submit" name="submit" value="update / save" class="button" onclick="checkForm()" />
instead of
<input type="submit" name="submit" value="update / save" class="button" onclick="return checkForm()" />
try changing
if(!document.registration.firstName.value)
into
if(firstName == "")
and(every)
picture.indexOf(str1) != -1
into
picture.search(str1) == -1
and check whether it works or not >.>

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