I have a code but I need a javascript validation that checks maximum upload file size like check if the uploaded file is increased 1-MB he show error file is increased chosse less then 1MB file ...
I have this code how use maximum file size regular expression and whar code I use in this code that check maximum size validation.
<form action="" method="post">
<script type="text/javascript">
function ValidateExtension() {
var allowedFiles = [".doc", ".docx", ".pdf"];
var fileUpload = document.getElementById("fileUpload");
var lblError = document.getElementById("lblError");
var regex = new RegExp("([a-zA-Z0-9\s_\\.\-:])+(" + allowedFiles.join('|') + ")$");
if (!regex.test(fileUpload.value.toLowerCase())) {
lblError.innerHTML = "Please upload files having extensions: <b>" + allowedFiles.join(', ') + "</b> only.";
return false;
}
lblError.innerHTML = "";
return true;
}
</script>
<input id="fileUpload" type="file" />
<br />
<span id="lblError" style="color: red;"></span>
<br />
<input type="submit" id="btnUpload" value="Upload" onclick="return ValidateExtension()" />
</form>
This should get you started.
function validate(el) {
var maxfilesize = 1024 * 1024, // 1 Mb
filesize = el.files[0].size,
warningel = document.getElementById( 'lbError' );
if ( filesize > maxfilesize )
{
warningel.innerHTML = "File too large: " + filesize + ". Maximum size: " + maxfilesize;
return false;
}
else
{
warningel.innerHTML = '';
return true;
}
}
.warning { font-style: italic; }
<form enctype="multipart/form-data" method="POST">
<input type='file' name='f' onchange='validate(this)'>
<div id='lbError' class='warning'></div>
<input type='submit' onsubmit='return validate()'/>
</form>
Related
Add file size validation.
Can you help me to update this javascript to add a valid file size of 2MB before uploading it using JavaScript?
<!DOCTYPE html>
<html lang="id">
<head>
<title></title>
<script>
var _validFileExtensions = ["pdf"];
function ValidateSingleInput(oInput) {
if (oInput.type == "file") {
var sFileName = oInput.value;
if (sFileName.length > 0) {
var blnValid = false;
for (var j = 0; j < _validFileExtensions.length; j++) {
var sCurExtension = _validFileExtensions[j];
if (sFileName.substr(sFileName.length - sCurExtension.length, sCurExtension.length).toLowerCase() == sCurExtension.toLowerCase()) {
blnValid = true;
break;
}
}
if (!blnValid) {
alert("Sorry, " + sFileName + " is invalid, allowed extensions are: " + _validFileExtensions.join(", "));
oInput.value = "";
return false;
}
}
}
return true;
}
</script>
</head>
<body>
File 1: <input type="file" name="file1" onchange="ValidateSingleInput(this);" /><br />
File 2: <input type="file" name="file2" onchange="ValidateSingleInput(this);" /><br />
File 3: <input type="file" name="file3" onchange="ValidateSingleInput(this);" /><br />
</body>
</html>
[![enter image description here][1]][1]
This article has everything you need to know on how to validate filesize using JS.
Validation of file size while uploading using JavaScript / jQuery
You can do it with the FILE API (check browser support).
files[0].size returns the size of the file in bytes.
var filesize = oInput.files[0].size
My program alerts me when I first start it up, and it won't convert when I click the 'Calculate!' button.
<div id="input">
<form method = "post" action = "hw07.php" name = "form">
Temperature: <input type="text" id="num" name="temperature"> <br />
<input type="radio" name="con" value="far" id="far"> Convert to Fahrenheit
<br />
<input type="radio" name="con" value="cel" id="cel"> Convert to Celcius
<br />
<input type="button" name="submit" value="Calculate!" id="submit">
</form>
</div>
<div id = "results"></div>
window.addEventListener("load", link_events, false);
function link_events() {
var temp = document.getElementById("num");
document.getElementById("submit").onclick = calculate(temp);
}
function calculate(temp) {
if(isNaN(temp)){
alert("Not numeric")
}
if (document.getElementById("far").checked) {
document.getElementById("results").innerHTML = "Temperature is" +
Math.round(num-32)*5/9;
}
else if (document.getElementById("cel").checked){
document.getElementById("results").innerHTML = "Temperature is" + Math.round(num*9/5)+32;
}
else
alert("choose a conversion");
return false;
}
I want it to alert me when I click the 'Calculate!' button and not when I start the program. It needs to print the converted value, but it's not even printing anything atm.
You have several problems in your code.
Element.onclick property should be a function, not a function result value
To get proper recalculation each time you press button, you need to get temperature value from input field inside function calculate (Also do not forget to parse it to Number type since it has String type)
The last one is the mysterious num variable which should be temp obviously
All this problem are solved in the code below. Hope this helps.
window.addEventListener("load", link_events, false);
function link_events() {
document.getElementById("submit").onclick = calculate;
}
function calculate() {
var temp = Number(document.getElementById("num").value);
if (isNaN(temp)) {
alert("Not numeric")
return
}
if (document.getElementById("far").checked) {
document.getElementById("results").innerHTML = "Temperature is " + Math.round(temp - 32) * 5 / 9;
} else if (document.getElementById("cel").checked) {
document.getElementById("results").innerHTML = "Temperature is " + Math.round(temp * 9 / 5) + 32;
} else {
alert("choose a conversion");
}
return;
}
<div id="input">
<form method = "post" action = "hw07.php" name = "form">
Temperature: <input type="text" id="num" name="temperature"> <br />
<input type="radio" name="con" value="far" id="far"> Convert to Fahrenheit
<br />
<input type="radio" name="con" value="cel" id="cel"> Convert to Celcius
<br />
<input type="button" name="submit" value="Calculate!" id="submit">
</form>
</div>
<div id = "results"></div>
just remove this line
window.addEventListener("load", link_events, false);
and change the link_events function
function link_events() {
var temp = document.getElementById("num");
calculate(temp.value);
}
and add onClick event to button
<input type="button" name="submit" value="Calculate!" id="submit" onclick="link_events()">
also i corected this function
function calculate(temp) {
if (isNaN(temp)) {
alert("Not numeric")
}
if (document.getElementById("far").checked) {
document.getElementById("results").innerHTML = "Temperature is" +
Math.round(temp - 32) * 5 / 9;
}
else if (document.getElementById("cel").checked) {
document.getElementById("results").innerHTML = "Temperature is" + Math.round(temp * 9 / 5) + 32;
}
else
alert("choose a conversion");
return false;
}
num is not a variable should be temp in Math.round()
I have a submit form that users are using to register:
<form method="post" action="<?php echo $_SERVER["PHP_SELF"]; ?>" name="form" onSubmit="return validate(this);">
<div class="form-group">
<input type="text" id="name" name="name" class="inputs" /><br />
<input type="text" id="email" name="email" class="inputs" /><br />
<input type="password" id="password" name="password" class="inputs" />
</div>
<input type="submit" class="btn1" name="register" value="Register" />
</form>
The JS code is checking if the data is entered correctly. If the user enters incorrect date the JS code is showing a message. Now I want to show a message when the data is entered correctly. I tried to add a row like if (errors.length < 0) but this didn't work. The JS code sends me the message for the "correct input" and the message "Dont use symbols...\n".
How can I make this working?
Here is my JS code:
<script type="text/javascript">
var ck_name = /[A-Za-z0-9. ]{3,25}$/;
var ck_email = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
var ck_password = /^[A-Za-z0-9!##$%^&*()_]{6,20}$/;
function validate(form)
{
var name = form.name.value;
var email = form.email.value;
var password = form.password.value;
var errors = [];
if (!ck_name.test(name))
{
errors[errors.length] = "Name error! .";
}
if (!ck_email.test(email))
{
errors[errors.length] = "Email error! .";
}
if (!ck_password.test(password))
{
errors[errors.length] = "Password error!";
}
if (errors.length > 0)
{
reportErrors(errors);
return false;
}
return true;
}
function reportErrors(errors)
{
var msg = "Dont use symbols...\n";
for (var i = 0; i<errors.length; i++) {
var numError = i + 1;
msg += "\n" + numError + ". " + errors[i];
}
alert(msg);
}
</script>
Errors.length never won't be minor of 0. You must use equal (==). This works! :-)
UPDATE
if (errors.length == 0) {
alert('Correct input');
}
That would be before the return true statement and after the if (errors.length > 0).
I created a form for uploading files to my Google Drive.
Now I need to validate and submit my form. So i want to validate the inputs first, and then submit, but i can't do it.. When clicking "Upload" both things happen at the same time. Could somebody help me?
HTML:
<div>
<form name= "myForm" id="myForm">
<label><b>Name</b></label>
<input id="id1" type="text" name="myName" placeholder="Name.." required />
<label><b>Email</b></label>
<input id="id1" type="email" name="myEmail" placeholder="Email.." required />
<label><b>Tel</b></label>
<input id="id1" type="tel" name="myTel" placeholder="Tel.." required />
<input id="id1" type="file" name="myFile" required />
<button id="button" onclick="myFunction();">Upload</button>
</form>
</div>
<div id="output"></div>
Javascript:
<script>
function myFunction() {
var upload = this.value='Uploading..';
google.script.run.withSuccessHandler(fileUploaded).uploadFiles(this.parentNode);
return false;
var inpObj = document.getElementById("id1");
if (inpObj.checkValidity() == false) {
document.getElementById("button").innerHTML = inpObj.validationMessage; return;
} else {
document.getElementById("button").innerHTML = upload;
}
}
function fileUploaded(status) {
document.getElementById('myForm').style.display = 'none';
document.getElementById('output').innerHTML = status;
}
</script>
Also, here is Server.gs:
function doGet(e) {
return HtmlService.createHtmlOutputFromFile('form.html');
}
function uploadFiles(form) {
try {
var dropbox = "Videos";
var folder, folders = DriveApp.getFoldersByName(dropbox);
if (folders.hasNext()) {
folder = folders.next();
} else {
folder = DriveApp.createFolder(dropbox);
}
var blob = form.myFile;
var file = folder.createFile(blob);
file.setDescription("Uploaded by " + "|" + form.myName + "|" + form.myTitle + "|" + form.myEmail);
return "Success.";
} catch (error) {
return error.toString();
}
}
I've some Javascript code. I included the jQuery file jquery-2.1.1.min.js and converted the whole Javascript code to jQuery code but when I executed this code I'm not able to POST the file. Due to which I'm not able to upload the file to the server using PHP. In firebug console I'm always getting blank. Can someone please help me in correcting this issue?
Original Javascript code :
<!DOCTYPE html>
<html>
<head>
<title>Take or select photo(s) and upload</title>
<script type="text/javascript">
function fileSelected() {
var count = document.getElementById('fileToUpload').files.length;
document.getElementById('details').innerHTML = "";
for (var index = 0; index < count; index ++) {
var file = document.getElementById('fileToUpload').files[index];
var fileSize = 0;
if (file.size > 1024 * 1024)
fileSize = (Math.round(file.size * 100 / (1024 * 1024)) / 100).toString() + 'MB';
else
fileSize = (Math.round(file.size * 100 / 1024) / 100).toString() + 'KB';
document.getElementById('details').innerHTML += 'Name: ' + file.name + '<br>Size: ' + fileSize + '<br>Type: ' + file.type;
document.getElementById('details').innerHTML += '<p>';
}
}
function uploadFile() {
var fd = new FormData();
var count = document.getElementById('fileToUpload').files.length;
for (var index = 0; index < count; index ++) {
var file = document.getElementById('fileToUpload').files[index];
fd.append('myFile', file);
}
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener("progress", uploadProgress, false);
xhr.addEventListener("load", uploadComplete, false);
xhr.addEventListener("error", uploadFailed, false);
xhr.addEventListener("abort", uploadCanceled, false);
xhr.open("POST", "savetofile.php");
xhr.send(fd);
}
function uploadProgress(evt) {
if (evt.lengthComputable) {
var percentComplete = Math.round(evt.loaded * 100 / evt.total);
document.getElementById('progress').innerHTML = percentComplete.toString() + '%';
} else {
document.getElementById('progress').innerHTML = 'unable to compute';
}
}
function uploadComplete(evt) {
/* This event is raised when the server send back a response */
alert(evt.target.responseText);
}
function uploadFailed(evt) {
alert("There was an error attempting to upload the file.");
}
function uploadCanceled(evt) {
alert("The upload has been canceled by the user or the browser dropped the connection.");
}
</script>
</head>
<body>
<form id="form1" enctype="multipart/form-data" method="post" action="Upload.aspx">
<div>
<label for="fileToUpload">Take or select photo(s)</label><br />
<input type="file" name="fileToUpload" id="fileToUpload" onchange="fileSelected();" accept="image/*" capture="camera" />
</div>
<div id="details"></div>
<div>
<input type="button" onclick="uploadFile()" value="Upload" />
</div>
<div id="progress"></div>
</form>
</body>
</html>
Converted above code to jQuery code as follows but getting blank in POST :
<!DOCTYPE html>
<html>
<head>
<title>Take or select photo(s) and upload</title>
<script type="text/javascript" charset="utf-8" src="jquery-2.1.1.min.js"></script>
<script type="text/javascript">
function fileSelected() {
var count = $('#fileToUpload').get(0).files.length;//$('#fileToUpload').size() may also work
$('#details').html("");
for (var index = 0; index < count; index ++) {
var file = $('#fileToUpload').get(0).files[index];//.get(0) gives you the js DOM object
var fileSize = 0;
if (file.size > 1024 * 1024)
fileSize = (Math.round(file.size * 100 / (1024 * 1024)) / 100).toString() + 'MB';
else
fileSize = (Math.round(file.size * 100 / 1024) / 100).toString() + 'KB';
$('#details').append('Name: ' + file.name + '<br>Size: ' + fileSize + '<br>Type: ' + file.type);
$('#details').append('<p>');
}
}
function uploadFile() {
var fd = new FormData();
var count = $('#fileToUpload').get(0).files.length;
for (var index = 0; index < count; index ++) {
var file = $('#fileToUpload').get(0).files[index];
fd.append('myFile', file);
}
$.ajax({url:"savetofile.php", type:'POST', success:uploadComplete, error:uploadFailed});
// abort is included in error, the second parameter passed to the error method would be statusText with value of abort in case of abort!
}
function uploadComplete(data) {
/* This event is raised when the server send back a response */
alert(data);
}
function uploadFailed(jqXHR, textStatus) {
if(statusText==="abort") {
alert("The upload has been canceled by the user or the browser dropped the connection.")
} else {
alert("There was an error attempting to upload the file.");
}
}
</script>
</head>
<body>
<form id="form1" enctype="multipart/form-data" method="post" action="Upload.aspx">
<div>
<label for="fileToUpload">Take or select photo(s)</label><br />
<input type="file" name="fileToUpload" id="fileToUpload" onchange="fileSelected();" accept="image/*" capture="camera" />
</div>
<div id="details"></div>
<div>
<input type="button" onclick="uploadFile()" value="Upload" />
</div>
<div id="progress"></div>
</form>
</body>
</html>
Thanks in advance.
If you want I can give you the code of PHP file as well.
You're not passing any data, this is what you're doing
$.ajax({
url : "savetofile.php",
type : 'POST',
success : uploadComplete,
error : uploadFailed
});
that, sends nothing, you have to actually add the data
$.ajax({
url : "savetofile.php",
type : 'POST',
data : fd,
success : uploadComplete,
error : uploadFailed
cache : false,
contentType : false,
processData : false
});