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();
}
}
Related
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 been working on a student registration form validation in JavaScript but it doesn't work at all. I have even tried writing all sorts of log statements for debugging but it seems the functions aren't being invoked at all(?).
It'd be helpful if you guys could let me know where I am going wrong with this.
Here is the code :
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript">
function allLetter() {
var name = document.querySelector("#name").value;
var letters = /^[A-Za-z]*$/;
if (name.test(letters)) {
return true;
} else {
alert("Not a valid Name");
return false;
}
}
function rollnumber() {
var roll = document.querySelector("#roll").value;
var phoneno = /^\d{7}$/;
if (roll.test(phoneno)) {
return true;
} else {
alert("Not a valid Roll Number");
return false;
}
}
function date() {
var date = document.querySelector("#date").value;
if (!date) {
return true;
}
else {
alert("Empty Date");
return false;
}
}
function check() {
var t1 = allLetter();
var t2 = rollnumber();
var t3 = date();
console.log(t1);
console.log(t2);
console.log(t3);
if (t1 && t2 && t3) {
alert("Registration Successful");
return true;
} else {
alert("One or More Fields are incorrectly set");
return false;
}
}
</script>
</head>
<body>
<h2>STUDENT REGISTRATION FORM</h2>
<form name="form1" method="post" onsubmit="return check()">
<label for="name">Name :</label>
<input type="text" id="name"><br>
<label for="roll">Roll No :</label>
<input type="text" id="roll"><br>
<label for="date">DOB :</label>
<input type="date" id="date"><br>
<input type="submit" value="Register">
</form>
</body>
</html>
here is my solution no javascript needed just html
<h2>STUDENT REGISTRATION FORM</h2>
<form name="form1" method="post">
<label for="name">Name :</label>
<input type="text" id="name" pattern="[A-Za-z\s]+" required><br>
<label for="roll">Roll No :</label>
<input type="text" id="roll" pattern="[0-9]+" required><br>
<label for="date">DOB :</label>
<input type="date" id="date" required><br>
<input type="submit" value="Register">
</form>
You inverted the use of .test method.
You should use regex on the left, because .test is a method of regexes.
Here your code working:
function allLetter() {
var name = document.querySelector("#name").value;
var letters = /^[A-Za-z]*$/;
if (letters.test(name)) {
return true;
} else {
alert("Not a valid Name");
return false;
}
}
function rollnumber() {
var roll = document.querySelector("#roll").value;
var phoneno = /^\d{7}$/;
if (phoneno.test(roll)) {
return true;
} else {
alert("Not a valid Roll Number");
return false;
}
}
function date() {
var date = document.querySelector("#date").value;
if (!date) {
return true;
}
else {
alert("Empty Date");
return false;
}
}
function check() {
var t1 = allLetter();
var t2 = rollnumber();
var t3 = date();
console.log(t1);
console.log(t2);
console.log(t3);
if (t1 && t2 && t3) {
alert("Registration Successful");
return true;
} else {
alert("One or More Fields are incorrectly set");
return false;
}
}
Then inside the onsubmit event you can remove the return and just use the method, the method will return directly true or false
<form name="form1" method="post" onsubmit="check();">
I think you should use the .test() method, like here.
So regex first, instead of name.test(letters) you should use letters.test(name).
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 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>
My code follows:.
<!doctype html>
<html lang="en">
<head>
<title>Testing the textarea</title>
<style type="text/css"></style>
<script type="text/javascript" src="validation.js"></script>
</head>
<body>
<div id="wrapper">
<span id="error_box" style="display:none;"></span>
<form name="storyTeller" method="get" action="#" onSubmit="return validateForm()">
<p class="title">
<label for="title">TITLE:</label>
<input type="text" id="title" name="title" required onBlur="validateTitle(title)"/>
</p>
<textarea name="entry" id="entry" rows="10" cols="45" onBlur="validateEntry(entry)">
</textarea>
<input type="submit" value="submit" />
</form>
</div>
</body>
</html>
Content of validation.js:
function validateTitle(title){/*validating the title*/
if (isNaN(document.getElementById('title').value)){
document.getElementById('title').style.background="#ccffcc";
document.getElementById('error_box').style.display="none";
return true;
}
else{
document.getElementById('error_box').innerHTML='Please enter a valid title';
document.getElementById('error_box').style.display="block";
document.getElementById('title').style.background="red";
return false;
}
}
function validateEntry(entry){/*validating the entry*/
var x=document.getElementById('entry').value;
x = x.trim();
if((x=="")||(x==null)){
document.getElementById('entry').style.background="red";
document.getElementById('error_box').innerHTML = 'Where is your story';
document.getElementById('error_box').style.display="block";
return false;
}
else{
document.getElementById('entry').style.background="#ccffcc";
document.getElementById('error_box').innerHTML='';
document.getELementById('error_box').style.display="none";
return true;
}
}
function validateForm(){/*validating the form*/
var error = 0;
if(!validateTitle('title')){
document.getElementById('error_box').style.display="block";
error++;
}
if(!validateEntry('entry')){
document.getElementById('error_box').style.display="block";
error++;
}
if(error > 0){
return false;
}
}
make the submit button as a normal button; and when it is clicked to call the final validation function, at the end of the function you must submit the form manually if everything is right
example :
<script>
function val(){
if(document.getElementById('tb').value != "")
document.getElementById('frm').submit();
else alert('fill the text field');
}
</script>
<form id="frm" action="#">
<input type="text" id="tb"/>
<input type="button" id="btn" value="submit" onclick="val()"/>
</form>
There is an error in your scrip in function validateEntry()
change line:
document.getELementById('error_box').style.display="none";
to line:
document.getElementById('error_box').style.display="none";
Modified your code so now it works better for both submit and blur events.
In your HTML source change both onblur attributes to onblur="validateEntry(this)" and then you can use this javascript:
function validateEntry(entry) { /*validating*/
var error_box = document.getElementById('error_box');
error_box.style.display = "none";
if (entry.name == "title") { // INPUT type="text"
if (!isNaN(entry.value)) {
error_box.innerHTML = 'Please enter a valid title';
error_box.style.display = "block";
entry.style.background = "#fee";
return false;
} else {
entry.style.background = "#ccffcc";
return true;
}
} else if (entry.name == "entry") { // TEXTAREA
var x = entry.value.trim();
if ((x == "") || (x == null)) {
error_box.innerHTML = 'Where is your story?';
error_box.style.display = "block";
entry.style.background = "#fee";
return false;
} else {
entry.style.background = "#ccffcc";
return true;
}
}
}
function validateForm() { /*validating the form*/
var form = document.forms['storyTeller'];
var error_box = document.getElementById('error_box');
var error = 0;
var error_msg = '';
if (!validateEntry(form['title'])) {
error++;
error_msg += error_box.innerHTML + '<br/>';
}
if (!validateEntry(form['entry'])) {
error++;
error_msg += error_box.innerHTML;
}
if (error > 0) {
error_box.innerHTML = error_msg;
error_box.style.display = "block";
return false;
} else {
error_box.style.display = "none";
return true;
}
}
jsfiddle