run.google.script only if form is complete - javascript

I'm trying to create a form using the google scripts that will not allow submission unless all the fields are entered. Currently, I use the "onclick" command to run a google script that send the form data and files to my google drive. However, I only want the form to be submittable if certain fields are filled in (those marked required). If I remove the google.script.run command from the "onclick" portion of the submit button, then the form creates alerts/messages that say the user must fill in the required form. These messages do not appear when the google.script.run command is included. I haven't figured out a way to make it so that the google.script.run command only runs if all fields are completed.
<!-- Include the Google CSS package -->
<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons.css">
<!-- You can also include your own CSS styles -->
<style>
form { margin: 40px auto; }
input { display:inline-block; margin: 20px; }
</style>
<form id="myForm" name="myForm">
<label for="myFirstName"> First Name *</label>
<input type="text" name="myFirstName" placeholder="First name" style="width: 150px;" required>
<fieldset>
<legend> Personal Information </legend>
<div class="inline form-group">
</div>
<div class="inline form-group">
<label for="myLastName"> Last Name* </label>
<input type="text" name="myLastName" placeholder="Last Name" style="width: 150px;" required>
</div>
<div class="inline form-group">
<label for="myEmail"> Email* </label>
<input type="email" name="myEmail" placeholder="" style="width: 150px;" required>
</div>
<div class="inline form-group">
<label for="visa"> Check if you will require visa assistance. Otherwise, ignore. </label>
<input type="checkbox" name="visa" value="Yes">
</div>
</fieldset>
<fieldset>
<legend> Documents </legend>
<div class="inline form-group">
<label for="CV"> CV* </label>
<input type="file" name="CV" required>
</div>
<div class="inline form-group">
<label for="CoverLetter"> Cover Letter </label>
<input type="file" name="CoverLetter">
</div>
</fieldset>
<p> </p>
<input id="submitbutton" type="submit" style="margin-left:450px" value="Submit Application"
onclick="this.value='Submitting...';
google.script.run.withSuccessHandler(fileUploaded).uploadFiles(this.parentNode);
return false;">
</form>
<div id="output"></div>
<script>
function fileUploaded(status) {
document.getElementById('myForm').style.display = 'none';
document.getElementById('output').innerHTML = status;
}
</script>
<style>
input { display:block; margin: 20px; }
</style>
The googlescript runs fine. I'm also aware of some similar questions about form validation. The google script specific ones do not use the same form format (they create the form in google script). I would like to make as minimal changes as possible to achieve the required functionality.
Any help would be appreciated.
Current code for jquery:
$('#submitbutton').on('click', function() {
$(this).val("Validating...");
//check for required fields
var emptyFields = $('[required]').filter(function() {
$(this).removeClass("warning");
if ($(this).val().length === 0){
$(this).addClass("warning")
return true
} else {
return false
}
});
if (emptyFields.length === 0) {
google.script.run.withSuccessHandler(fileUploaded).uploadFiles(this.parentNode);
} else{
$(this).val("Submit Application")
}
});

Your form is submitting before the messages can appear. One way to handle this is to change your button to a button (instead of type submit), and then trigger an event on click. Check for your validation, and if everything passes, submit your form.
example:
change your button to:
<input id="submitbutton" type="button" style="margin-left:450px" value="Submit Application" >
and the click event:
$('#submitbutton').on('click', function() {
$(this).val("Validating...");
//check for required fields
var emptyFields = $('[required]').filter(function() {
$(this).removeClass("warning");
return $(this).val().length === 0;
});
if (emptyFields.length > 0) {
emptyFields.addClass("warning");
} else {
google.script.run.withSuccessHandler(fileUploaded).uploadFiles(this.parentNode);
$('#myForm').submit();
}
});
and CSS
.warning {border: 1px solid red; }

Related

Form validation on blur

I have 5 input fields and I want them to validate on blur, and show either an error or success message, but through DOM scripting and not with an alert box. I've tried several different codes, even just small bits and pieces to see if it's correctly interacting with my html but it doesn't seem to work.
So far, I have a small code to test if it even runs, and it's supposed to show an alert box but it does not. I would prefer to not use any innerHTML and use all functions within the javascript only.
My html:
<div id=fNID>
<label for="firstNameID">First Name: </label>
<input id="firstNameID" type="text" name="firstNameA" value="" />
<span> </span>
</div>
<div id=lNID>
<label for="lastNameID">Last Name: </label>
<input id="lastNameID" type="text" name="lastNameA" value="" />
<span> </span>
</div>
My javascript:
firstNameID = document.surveyForm.getElementById("firstNameID");
document.surveyForm.getElementById(fN).addEventListener("blur", validateName);
function validateName() {
var nameRegEx = /[a-zA-Z]+/;
var firstNameID = document.getElementById("firstNameID");
if (fN.matches(nameRegEx)) {
alert("Success!")
} else {
alert("error")
}
}
window.addEventListener("load", setupForm, false);
}
Bootstrap has a nice pattern for input validation. They use divs following the input: one for valid input, one for invalid input, making the appropriate one visible:
<div class="form-group">
<label for="uname">Username:</label>
<input class="form-control" id="uname">
<div class="valid-feedback">Valid.</div>
<div class="invalid-feedback">Please fill out this field.</div>
</div>
Bootstrap's CSS classes modify the display based on the input's pseudo-classes :valid and :invalid.
You can set these pseudo-classes in JavaScript with the setCustomValidity() method.
input.setCustomValidity("input is invalid")
will assign the :invalid pseudo-class to the input.
input.setCustomValidity("")
will assign the :valid pseudo class.
A working example:
const input = document.getElementById('uname');
function makeValid() {
input.setCustomValidity('');
}
function makeInvalid() {
input.setCustomValidity('a problem');
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
<h3 class="m-2">Bootstrap input with validation</h3>
<form class="was-validated mx-2">
<div class="form-group">
<label for="uname">Username (required):</label>
<input type="text" class="form-control" id="uname" placeholder="Enter username" name="uname">
<div class="valid-feedback">Valid.</div>
<div class="invalid-feedback">This field is invalid.</div>
</div>
</form>
<div class="m-2">
<p>Use setCustomValidity() to change input state:</p>
<button onclick="makeValid();">:valid</button>
<button onclick="makeInvalid();">:invalid</button>
</div>
It's also worth noting that most browsers have native support for displaying validation messages on inputs. Here's an example that doesn't use any Bootstrap features:
const input = document.getElementById('uname');
function makeValid() {
input.setCustomValidity('');
}
function makeInvalid() {
input.setCustomValidity('this is invalid');
}
body {
background-color: #aaa;
}
.m-2 {
margin: .5rem;
}
.mt-5 {
margin-top: 1rem;
}
<body>
<h3 class="m-2">Generic input with validation</h3>
<form class="mt-5">
<label for="uname">Username:</label>
<input type="text" id="uname" placeholder="Enter username" name="uname">
<p>Use setCustomValidity() to change input state:</p>
<button onclick="makeInvalid();">input:invalid</button>
</form>
<div class="m-2">
<button onclick="makeValid();">input:valid</button>
</div>
</body>

HTML5 validation does not trigger when fields are not accesible

I have a form with multiple fields, and I need to scroll 10-15 fields until the submit button. I want to check if the form is valid or not via jquery. If the first field of my form is required and I click on the submit button the field borders are going red but the message is not displayed. If I remove all the required fields from the top and just add the last fields as required the message is displayed. If I resize the browser to be able to see the first field when press the submit the validation message is displayed. Does this function (reportValidity) work with not accessible fields?
$('form').each(function() {
var $form = $(this);
$form.find(':submit').on({
'mousedown': function(e) {
var form = $(this).closest('form')[0];
if (form.checkValidity()) {} else {
form.reportValidity();
}
},
});
});
.test {
margin-bottom: 300px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<div class="test">
<label>Email:
<input name=email type=text required title="enter your email">
</label>
<br>
</div>
<div class="test">
<label>Email:
<input name=email type=text required title="enter your email">
</label>
<br>
</div>
<div class="test">
<label>Email:
<input name=email type=text required title="enter your email">
</label>
<br>
</div>
<input type=submit>
</form>
It can be solved by adding event.preventDefault() before the reportValidity() call.

Simple use of the 'required' attribute but also validate the form (to exclude '#')

I’m trying to create a form that ensures the name input field excludes the ‘#‘ symbol but also has the same box appear prompting the user to fill in the field if empty. I assume the box may differ per browser.
To explain my demo further, see this default form:
<form id='form-id' action="/" method="post">
<div class="subscribe-form">
<div class="form-section">
<div>
<input type="text" name="first_name" placeholder="name here" id="name-id" required />
</div>
<div>
<input type="text" name="email" placeholder="Email*" id="email-id" required />
</div>
<input id='checkbox-id' type="checkbox" required /> *check here
</div>
<button type="submit" value="Subscribe">submit</button> <!-- WITH input type submit -->
</div>
</form>
Clicking the submit button will only submit if all fields are completed, but it won’t check if the name field includes an ‘#‘. I can’t edit it to only submit if the field doesn’t include an ‘#‘.
But this demo:
<form id='form-id' action="/" method="post">
<div class="subscribe-form">
<div class="form-section">
<div>
<input type="text" name="first_name" placeholder="name here" id="name-id" required />
</div>
<div>
<input type="text" name="email" placeholder="Email*" id="email-id" required />
</div>
<input id='checkbox-id' type="checkbox" required /> *check here
</div>
<button onclick="checkName()" type="button" value="Subscribe">submit</button> <!-- changed from input type submit -->
</div>
<script>
let form = document.getElementById('form-id'),
ecsName = document.getElementById('name-id'),
ecsEmail = document.getElementById('email-id'),
ecsCheckbox = document.getElementById('checkbox-id');
function checkName() {
let name = ecsName.value,
email = ecsEmail.value;
if(name.includes('#')) {
alert('includes #');
} else if (name == '' || email == '') {
alert('please fill in your details');
} else if (ecsCheckbox.checked == false) {
alert ('unckeded');
} else {
form.submit();
}
}
</script>
</form>
Includes javascript that ensures all fields are completed, but I don’t like the alert and want the same prompt box to appear as with the former form.
Is there any way of doing this? I’m essentially trying to not tamper with the form and let the default settings do most of the work if possible. Also, another quick question - should required be required='required'? Thanks for any help here.

custom web component with vanilla javascript and validations

I am working in a web component, but I want to add it validations with javascript constrains, but It looks like this just work for inputs elements and my main container is a div.
I am not sure if it exists some workaround for this. I had tried to use an input with display none or size 0x0, but this dislike to me and does not work good.
<form action="">
<input type="text" required="" name="field1">
<input type="text" required="" name="field2">
<div name="mycustominput" myValidation="true">
<!--
children html elements render list and another things
I want to validate this with the form
-->
</div>
</form>
Can you help me?
if you try some inputs validate together like this:
<form id="passwordForm" novalidate>
<fieldset>
<legend>Change Your Password</legend>
<ul>
<li>
<label for="password1">Password 1:</label>
<input type="password" required id="password1" />
</li>
<li>
<label for="password2">Password 2:</label>
<input type="password" required id="password2" />
</li>
</ul>
<input type="submit" />
</fieldset>
js
var password1 = document.getElementById('password1');
var password2 = document.getElementById('password2');
var checkPasswordValidity = function() {
if (password1.value != password2.value) {
password1.setCustomValidity('Passwords must match.');
} else {
password1.setCustomValidity('');
}
};
password1.addEventListener('change', checkPasswordValidity, false);
password2.addEventListener('change', checkPasswordValidity, false);
var form = document.getElementById('passwordForm');
form.addEventListener('submit', function() {
checkPasswordValidity();
if (!this.checkValidity()) {
event.preventDefault();
//Implement you own means of displaying error messages to the user here.
password1.focus();
}
}, false);
this link (http://www.html5rocks.com/en/tutorials/forms/constraintvalidation/) is yours.
have a good day.

Show/hide fieldset based on radio button using Javascript

I'm trying to have the email/phone number section of a contact form hidden or visible depending on whether the user picks the phone or email radio button, but I cannot figure out why it is not working for me.
I've searched through stack overflow & w3Schools, and I'm pretty certain I'm using the correct syntax but it will still not show/hide depending on the radio buttons.
Any help would be hugely appreciated!
HTML
<form name="contactForm" id="contactForm" method="post" action="result.php">
<fieldset>
<!-- Client's contact details -->
<legend>Contact Details</legend>
<label for="fullname">Full Name:</label>
<input type="text" name="contact" id="fullname" required>
<label>Preferred contact method:</label>
<input type="radio" name="contact" value="rdoPhone" id="rdoPhone" checked="checked" onclick="cPhone()" >Phone
<input type="radio" name="contact" value="rdoEmail" id="rdoEmail" onclick="cEmail()" >Email
<label for="phonenumber">Phone Number:</label>
<input type="text" name="contact" id="phonenumber">
<label for="email">Email:</label>
<input type="text" name="contact" id="email">
</fieldset>
</form>
CSS
#email {
display:none;
}
#phonenumber {
display:none;
}
Javascript
function cPhone() {
if (document.getElementById("rdoPhone").checked)
{ document.getElementById("phonenumber").style.display = "block"; }
}
function cEmail(){
if (document.getElementById("rdoEmail").checked)
{ document.getElementById("email").style.display = "block"; }
}
Since phone number is checked by default, you should not hide it initially.
You don't have to check for the checked property on click of a radio in a radio button group, because a click will always select it.
You can use a common function for this purpose as follows -
apply the class hide given below initially for the email.
call the function showHide(this) given below onClick of both radios
css
.hide {
display:none;
}
js
function showHide(elm) {
var phone = document.getElementById("phonenumber");
var email = document.getElementById("email")
if(elm.id == 'rdoPhone'){
phone.classList.remove('hide');
email.classList.add('hide');
}
else
{
phone.classList.add('hide');
email.classList.remove('hide');
}
}
Demo
It is faster to apply it directly in javascript:
$('#id-element').css('display', 'block');
$('#id-element').css('display', 'none');

Categories

Resources