HTML input validation happens after button onClick is triggered - html

I have a simple form and the problem is that the validation happens after the click event is registered, thus triggering the doSomething() function. I would like the email validation to stop the user from submitting the form so that the function will not be triggered. How would I do that?
<form>
<input type="email" placeholder="your email here" required/>
<button type="submit" onClick="doSomething()">Submit</button>
</form>
<script>
function doSomething(){
// gets triggered even when the email does not pass validation
console.log('Doing work..');
}
</script>
JSFiddle

You could use the onSubmit attribute in the form, which will only call your function when all fields are validated.
<form onSubmit="doSomething()">
<input type="email" placeholder="your email here" required/>
<input type="submit"/>
</form>
<script>
function doSomething(){
// gets triggered even when the email does not pass validation
console.log('Doing work..');
}
</script>
View this question to understand how to stop the form from submitting.
Thanks,

Related

html5 e-mail validation failed

I have this simple input field for e-mail addresses:
<form>
<input type="email" placeholder="E-Mail" required>
<input type="submit" value="Send" />
</form>
If you write "max#mail.de", you can submit the form, because the email is valid.
If you write "max#.de", you can't submit the form, because the email is invalid.
But!
If you write "max#i9", you can submit the form, too. But the mail is invalid. Why?
And how can I fix it?
Because max#i9 is a valid email as it stated in this article.
You can "fix" it by adding your own email pattern, see this tutorial:
<form>
<input type="email" pattern="/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+#[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/" required />
</form>
Here's a more detailed question about Why does HTML5 form validation allow emails without a dot?
<form>
<input pattern="[a-zA-Z0-9.-_]{1,}#[a-zA-Z.-]{2,}[.]{1}[a-zA-Z]{2,}$"
type="text" required />
<input type="submit" value="Send" />
</form>
This is because HTML5 type="email" validator is only find # symbol in your input string. If it is found your form will submitted else it won't submitted.
To avoid this you have to use javaSctipt form Validation like this :-
function validateemail()
{
var x=document.myform.email.value;
var atposition=x.indexOf("#");
var dotposition=x.lastIndexOf(".");
if (atposition<1 || dotposition<atposition+2 || dotposition+2>=x.length){
alert("Please enter a valid e-mail address \n atpostion:"+atposition+"\n dotposition:"+dotposition);
return false;
}
}
HTML can't help you with data validation, you can learn js to do that

HtmlService Spreadsheet form refresh

I have a form ModalForm on a Google Sheet that inserts rows into the sheet. It's been working fine for months. Starting last week after submitting the form the form disappears and doesn't re-display. I'm not sure why. It executes the insert into the spreadsheet fine. I just never get the form back to insert the next record.
In my Index file, the form code:
<form id="myReceiveForm" name="receive" onsubmit="writeLine()">
Scanner Name : <input id="user" name="user" type="text" required /> <br> <br>
Reference Number: <input id="reference" name="reference" type="text" required /> <br> <br>
Location: <input id="location" name="location" type="text" pattern="[A-Z]{1,3}\-[A-Z]{1,2}\-\d{1,3}\-\d{1,2}" title="Location not in correct format." required/>
<button type="button" value="change" onclick="changeLocation()" >Change Location</button><br> <br>
Product SKU: <input id="sku" name="sku" type="text" value="" autofocus /> <br> <br>
<input type="submit" value="Submit" >
</form>
<script type="text/javascript">
function onSuccess() {
document.getElementById("sku").value = '';
document.getElementById("sku").focus();
return false;
}
function onFailureM(error) {
alert("Invalid Sku");
//alert("SKU" + document.getElementById("sku ").value +" doesn't exist.");
document.getElementById("sku").value = '';
document.getElementById("sku").focus();
}
window.writeLine = function () {
google.script.run
.withSuccessHandler(onSuccess)
.withFailureHandler(onFailureM)
.appendRowstoSheet(document.forms[0]);
}
</script>
In My .gs file:
function openReceiving() {
var html = HtmlService.createHtmlOutputFromFile('index');
SpreadsheetApp.getUi().showModalDialog(html, '3PL RECEIVING');
Remove onsubmit="writeLine()" from the upper form tag. Change the submit button:
<input type="submit" value="Submit" >
to a regular button with an event:
<input type="button" value="Submit" onmouseup="writeLine()">
This should fix the problem. On Nov. 12th, 2015 Google migrated to IFRAME mode.
All new scripts will default to IFRAME sandbox mode unless NATIVE mode is explicitly specified.
Google Apps Script Sunset Scedule
This is what probably caused your problem. The form submit causes a form tag to disappear. This is expected behavior that has been in place for a long time in regular HTML. But for a long time, HTML Service overrode that behavior. Now, IFRAME mode is more like regular HTML behavior.
In the SKU input field, try adding an onchange attribute if you need the form to submit after the last field is updated:
<input id="sku" name="sku" type="text" value="" autofocus onchange="writeLine()"/>
onchange Event - Reference information
List of all the events

HTML5 form is not getting submitted

I have the following code to submit a form. If I use the event listener function name as submit, the form does not get submitted. If I use any other name, it will. Should not I use any HTML5 keyword like submit in JavaScript as function name? In this case submit is a HTML5 keyword which can be used as a type of any INPUT element.
<form onsubmit="submit()">
<input type="email" name="email" />
<input type="submit"/>
</form>
function submit() {
var f = $('form').serialize();
alert(f);
}
You're already using jQuery here so a more elegant solution to the whole problem would be:
// HTML
<form name="my-form">
<input type="email" name="email" />
<input type="submit"/>
</form>
Then have a separate JS file:
//Js
$(document).ready(function(){
$('form[name="my-form"]').submit(function(e){
var f=$(this).serialize();
alert(f);
});
});
This also gives you extra options to prevent the form from submitting cleanly; add this at the end of the submit(){ } function.
e.preventDefault();
Update
As the OP pointed out the original question was whether the function name submit() can be used as the onsubmit attribute in a form.
This answer suggests that it cannot, as carrying out the following:
document.form['my-form'].submit();
Would be a valid way to trigger submission of the form; thus that method name can't then be included in the HTML. I am searching now for a better source to confirm this for sure I have found a similar source on Mozilla Developer Network which confirms the code above but doesn't explicitly define that the keyword submit cannot be used.
You know, there is another way to do this. You could separate your html from javascript enritelly.
<form id="form">
<input type="email" name="email" />
<input type="submit"/>
</form>
//Rest of your code
<script>
$(function() {
$('#form').submit(function() {
var f = $('#form').serialize();
// do your stuff
return true; // return false to cancel form action
});
});
</script>

Do Not Load Page After Form Submit

I have created a basic HTML contact form using cgimail and everything works, but I can't get it to keep from redirecting somewhere after the form is submitted. I'm trying to instead use a bootstrap alert at the top of the page.
How do I get the form to submit, then keep it from redirecting?
here's the code:
<form method="post" action="/cgi-bin/cgiemail/forms/email.txt">
<fieldset>
<h2 id="contact-header">Contact</h2>
<label>Name:</label>
<input type="text" name="yourname" placeholder="" autofocus>
<label>Email Address:</label>
<input type="email" name="email" value="" placeholder="">
<label>Phone:</label>
<input type="tel" name="phone" value="" placeholder="">
<label>Message:</label>
<textarea name="message" rows="2"></textarea>
<br>
<button type="submit" id="formSubmit" class="btn">Send</button>
<input type="hidden" name="success" value="">
</fieldset>
</form>
Thanks,
Ryan
The "action" attribute in your form is telling it to send the browser over to that email.txt, which would then have control over whether or not to redirect you to another page. By default it would at least redirect you to the email.txt page for the post, but odds are cgi is doing extra stuff when posting to that page.
Using jQuery AJAX, you can do the following (this code skips error checking):
$('form').submit(function() {
var data = { };
data.yourname = $(this).find('input[name="yourname"]').val();
data.message = $(this).find('textarea[name="message"]').val();
// do the same as above for each form field.
$.post("/cgi-bin/cgiemail/forms/email.txt", data, function() {
//add the alert to the form.
$('body').prepend('div class="alert">Success!</div>');
});
return false;
});
You have two straight-forward choices. You can use jQuery and its forms plugin to turn this into an ajax operation or you can roll your own equivalent. It would look something like this (using jQuery):
$('form').submit(function() {
... get all values.
... ajax post the values to the server.
return false;
});
If you're using jQuery, then you could try cancelling the submit event. First give your form an id
HTML:
<form id="myform" ...
JavaScript:
$('#myform').on('submit', function(e) {
e.preventDefault();
$.ajax({
url: '/cgi-bin/cgiemail/forms/email.txt',
type: 'post',
data: $(this).serialize()
});
return false;
});

HTML5 validation when the input type is not "submit"

I'm using HTML5 for validating fields. I'm submitting the form using JavaScript on a button click. But the HTML5 validation doesn't work. It works only when then input type is submit. Can we do anything other than using JavaScript validation or changing the type to submit?
This is the HTML code:
<input type="text" id="example" name="example" value="" required>
<button type="button" onclick="submitform()" id="save">Save</button>
I'm submitting the form in the function submitform().
The HTML5 form validation process is limited to situations where the form is being submitted via a submit button. The Form submission algorithm explicitly says that validation is not performed when the form is submitted via the submit() method. Apparently, the idea is that if you submit a form via JavaScript, you are supposed to do validation.
However, you can request (static) form validation against the constraints defined by HTML5 attributes, using the checkValidity() method. If you would like to display the same error messages as the browser would do in HTML5 form validation, I’m afraid you would need to check all the constrained fields, since the validityMessage property is a property of fields (controls), not the form. In the case of a single constrained field, as in the case presented, this is trivial of course:
function submitform() {
var f = document.getElementsByTagName('form')[0];
if(f.checkValidity()) {
f.submit();
} else {
alert(document.getElementById('example').validationMessage);
}
}
You should use form tag enclosing your inputs. And input type submit.
This works.
<form id="testform">
<input type="text" id="example" name="example" required>
<button type="submit" onclick="submitform()" id="save">Save</button>
</form>
Since HTML5 Validation works only with submit button you have to keep it there.
You can avoid the form submission though when valid by preventing the default action by writing event handler for form.
document.getElementById('testform').onsubmit= function(e){
e.preventDefault();
}
This will give your validation when invalid and will not submit form when valid.
I may be late, but the way I did it was to create a hidden submit input, and calling it's click handler upon submit. Something like (using jquery for simplicity):
<input type="text" id="example" name="example" value="" required>
<button type="button" onclick="submitform()" id="save">Save</button>
<input id="submit_handle" type="submit" style="display: none">
<script>
function submitform() {
$('#submit_handle').click();
}
</script>
I wanted to add a new way of doing this that I just recently ran into. Even though form validation doesn't run when you submit the form using the submit() method, there's nothing stopping you from clicking a submit button programmatically. Even if it's hidden.
Having a form:
<form>
<input type="text" name="title" required />
<button style="display: none;" type="submit" id="submit-button">Not Shown</button>
<button type="button" onclick="doFancyStuff()">Submit</button>
</form>
This will trigger form validation:
function doFancyStuff() {
$("#submit-button").click();
}
Or without jQuery
function doFancyStuff() {
document.getElementById("submit-button").click();
}
In my case, I do a bunch of validation and calculations when the fake submit button is pressed, if my manual validation fails, then I know I can programmatically click the hidden submit button and display form validation.
Here's a VERY simple jsfiddle showing the concept:
https://jsfiddle.net/45vxjz87/1/
Either you can change the button type to submit
<button type="submit" onclick="submitform()" id="save">Save</button>
Or you can hide the submit button, keep another button with type="button" and have click event for that button
<form>
<button style="display: none;" type="submit" >Hidden button</button>
<button type="button" onclick="submitForm()">Submit</button>
</form>
Try with <button type="submit"> you can perform the functionality of submitform() by doing <form ....... onsubmit="submitform()">
2019 update: Reporting validation errors is now made easier than a the time of the accepted answer by the use of HTMLFormElement.reportValidity() which not only checks validity like checkValidity() but also reports validation errors to the user.
The HTMLFormElement.reportValidity() method returns true if the element's child controls satisfy their validation constraints. When false is returned, cancelable invalid events are fired for each invalid child and validation problems are reported to the user.
Updated solution snippet:
function submitform() {
var f = document.getElementsByTagName('form')[0];
if(f.reportValidity()) {
f.submit();
}
}
HTML5 Validation Work Only When button type will be submit
change --
<button type="button" onclick="submitform()" id="save">Save</button>
To --
<button type="submit" onclick="submitform()" id="save">Save</button>
Try this out:
<script type="text/javascript">
function test
{
alert("hello world"); //write your logic here like ajax
}
</script>
<form action="javascript:test();" >
firstName : <input type="text" name="firstName" id="firstName" required/><br/>
lastName : <input type="text" name="lastName" id="lastName" required/><br/>
email : <input type="email" name="email" id="email"/><br/>
<input type="submit" value="Get It!" name="submit" id="submit"/>
</form>