Submit HTML5 Form using Javascript and validate its inputs - javascript

I'm writing form and adding html5 validation attributes to its input like "required", "autofocus". I use Javascript to submit the form using document.myForm.submit() but it doesn't validate the form against the html5 validation attributes as they aren't there.
Any Suggestions?

It appears that triggering a click on the submit button does have the correct effect: http://jsfiddle.net/e6Hf7/.
document.myForm.submitButton.click();
and in case you don't have a submit button, add an invisible one like:
<input type="submit" style="display:none" name="submitButton">

The pimvdb's answer is based on a workaround to include a hidden submit button.
HTML5 provides javascript functions to achieve the same thing without a submit button. As Tigraine pointed out, Mozilla documents two validity checking methods for 'form' elements:
checkValidity() return true/false and doesn't show anything to the end user
reportValidity() return true/false and ALSO shows the validation messages to the end user (like the normal submit button click does)
<!DOCTYPE html>
<html>
<body>
<form name="testform" action="action_page.php">
E-mail: <input type="email" name="email" required><br/>
Report validity<br/>
Check validity<br/>
Submit
</form>
</body>
</html>

Why not simply call the validation manually before you do document.myForm.submit()
What validation framework do you use and what AJAX library?
In case you use jQuery here is the code to prevent the submit:
$('#myForm').submit(function(evt) {
if (! $('#myForm').validate()) {
evt.preventDefault();
}
});
And trigger the submit through:
$('#myForm').submit();
This would call the validation whenever submit is triggered.. And if the validation fails it prevents the submit from executing.
But I'd look at your validationframework as it usually should do this already
In case you don't use any JavaScript framework you may want to have a look at: element.checkValidity(); and how to invoke the HTML5 validation from JavaScript before even calling submit.

Related

Preventing form submission in jquery when for is submitted through javascript .submit

I am trying to prevent a form submission from happening using the event.preventDefault() in JS. While this works fine on a standard form submission, it seems to not be stopping the submission when the form is submitted externally by JS.
Here is an example HTML form that I am using:
<form id="demo12" method="post">
<input type="hidden" id="testID" name="testID" value="42">
</form>
Click this sentence to submit the form
And here is the included javascript/jquery file that is trying to catch this form being submitted:
$("[id^='demo']").submit(function (event) {
event.preventDefault();
// Then there is some ajax code here
}
Due to the nature of the form being added in through Jinja, there are multiple similar forms. I want to catch any form that starts with 'demo' in the id field and run some AJAX to fetch some new information from the server.
This has worked for me in the past, but the only difference is instead of there being a submit button, the form is being submitted separately through an html hyperlink tag. Is JQuery not able to catch the event of the form submission when it is submitted like this?
Currently when I do this, it just posts the form to the same html page and it the jquery function never occurred. I do see in debugging, through in the browser, that the jquery is listening properly and recognizes the form as something it is listening for to be submitted.
$('[data-submit]').on('click', e => {
$(e.target.dataset.submit).trigger('submit');
});
$('#demo12').on('submit', e => {
console.log('you submitted me!');
e.preventDefault();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="demo12" method="post">
<input type="hidden" id="testID" name="testID" value="42">
</form>
Click this sentence to submit the form
Rather than calling the native submit event, trigger the submit event on the form. This way, you can process it and conditionally cancel it.

javascript call before submit using thymeleaf does not work as expected

I am new to javascript so it might be a simple question for many.
I have used form sumbit in thymeleaf and am trying to add a JS validation before the form is submitted to the spring mvc controller. I can perform these two actions separately (individual tasks). However I could not really make them work one after the other (js function and form submit). Submit action is triggered by a button inside the form.
<form th:action="#{/user/trigger}" th:object="${triggers}" method="post">
<input type="hidden" name="tradeDate" th:value="${trigger.id.tradeDate}">
<button type="submit" id="ignore" name="action" value="ignoreOrder" class="btn btn-primary btn-sm">Ignore</button>
</form>
The js function is like below:
$(".ignore").click(function() {
//do some processing;
return false;
});
So can someone can help me to rewrite this code which will first call the JS function and submit the form to the java spring mvc controller? Thanks in advance.
The issue with your approach is that after your java-script is validating the code, your html 'submit' button is submitting the form as they're executing one after another. You haven't done anything to prevent the form submission after the validation is getting failed.
To overcome this issue, what you can do is to submit the form through your JavaScript code manually only when your validation is successful.
So your code will look something like this -
1.) Changes in Html code, instead of creating the button type as 'submit', make it as a normal button and run your javascript validation function on its click -
<form th:action="#{/user/trigger}" th:object="${triggers}" id="myForm" method="post">
<input type="hidden" name="tradeDate" th:value="${trigger.id.tradeDate}">
<button type="button" id="ignore" name="action" onclick="myValidationFunction()" value="ignoreOrder" class="btn btn-primary btn-sm">Ignore</button>
</form>
2.) Changes in Javascript code, now after clicking on the above button your javascript validation function will execute and after the validation is successful submit the form manually using the form id, something like this -
function myValidationFunction(){
if( some_condition ){
//validation failed
return;
}
//validation success , when above mentioned if condition is false.
$("#myForm").submit(); // Submit the form
}
For more information about using submit in jquery, refer the official documentation -
https://api.jquery.com/submit/
for jquery, it return a list, so:
$('#search_form')[0].submit();

Ajax call on form submission - MVC 5

The Goal:
Use an ajax call to either bring back information from database if the user supplied correct information, or if the user is a new user then it will return redirectToAction and send the user to another form. I want to do all of this using either parsley or bootstrap validator (I want to use these tools so that I can put the validator in the input and once I click on submit it will validate the form, but will not submit it. I also want it to have the same look, so the fields highlight similar to http://1000hz.github.io/bootstrap-validator/ The ajax call will handle the decision)
The problem:
Here is a similar form:
<form action="" id="application">
First Name: <input type="text" name="first" required/>
Last Name: <input type="text" name="last" required/>
<button type="submit">Submit</button>
</form>
When one clicks on this form, if the user has not supplied the first and last name it will not submit the form.
What I want it to do is if the user has supplied this information it will not go to the action but will instead execute the ajax call and never submit the form from the button press similar to $(button).click(function (){//do stuff});(the ajax call will handle the submission, my guess here is that we can substitute this ajax call for any JavaScript function).
Finally:
I have read about the e.preventdefault but it did not seem to work for me. How can I get the form to validate the inputs but never actually submit (unless the ajax allows it to). Can you give me an example of how I would do this? Or is this something that cannot be done? Should I do something similar to this Validate Form preventing form submission
Add an onsubmit event on the form, for example,
<form onsubmit = "DoSubmit(this);return false;">
DoSubmit: function()
{
//validate the form and decide submit or not
if($(form).valid())
{//if form valid, this is done by form validation itself
$(form)[0].submit();
}
else
{
//do nothing or do whatever
}
}

Submit Form Without Javascript

I have a form that relies on javascript to do all the client side form validation. The form is submitted via javascript if all the fields are correctly filled in as opposed to using a standard "submit" button:
<button name="button" type=button onclick="validateReqFields('mForm', 'username, password, compPassword, firstName, lastName');">Register</button>
document[formName].submit();
If the client has javascript disabled, all of the form validation is done server side (its actually performed again regardless but that doesn't really matter). The problem lies with using a button with a type of button instead of submit. It works perfect with javascript, but how do I get around this when javascript is not available? If I use a submit button along with the javascript then it submits the form with each button press and doesn't work properly.
Use a submit button instead of the "button" button, and then have your validateReqFields function return false if the form is not valid.
Then take out the form submit from the validateReqFields if you like.
This way
If the form is valid, then the button click will bubble and the form will submit
If the form is invalid, then the javascript will cancel the button click
If javascript is disabled, then it will be submitted to the server as a fallback
Change the type attribute to submit.
<button name="button" type="submit" ... />
Use the <noscript></noscript> tags to define a "normal" submit-button when javascript is disabled.
You could maybe use the <noscript> tag and encapsulate the above code with the button type as submit. If the client has js, the code inside the noscript will be ignored.

Hitting enter in any textbox in chrome triggers the form submit, even when there is no submit button

I am building a site which uses jQUery validation plugin and want things validated before submitting the form. My code looks like follows
<form>
<input type="button" value="Submit the Form" onclick="validateAndSubmit()" />
</form>
<script language="javascript">
function validateAndSubmit(){
//do some validation and then submit
}
</script>
In Firefox, this works perfectly. In Chrome, when I hit enter anywhere in the page, the form submit is triggered and validation doesn't work either. Is there something to avoid this ? Shouldn't the browser not submit a form when we hit an enter if there is no submit button?
use this syntax:
<form onsubmit="return validateAndSubmit()">
...
if you need to catch the return-key maybe you can handle it by binding an keydown event to the input and perform some action on keyCode #13
Try this method:
<form onsubmit="return validateAndSubmit(this);">
<input type="submit" value="Submit the Form"/>
</form>
<script language="javascript">
function validateAndSubmit(form_obj){
if(some_variable == 'correct_value') {
form_obj.submit();
return true;
} else {
alert('Wrong value');
return false;
}
//do some validation and then submit
}
</script>
I'm not sure if there's a standard regarding this or not.
Regardless, you can save yourself the trouble altogether by simply adopting a stronger strategy: implement the validation as an onsubmit action on the form, rather than an onclick action for the button. I almost never use buttons in forms; having to do so for yours would only throw me off, and that's not good for users.
So anyway. Form onsubmit is the way to go. And I'd appreciate it if you used unobtrusive Javascript instead of the HTML attributes :)

Categories

Resources