Launch browser's validation and error messages without submit - javascript

I'm trying to use html5 validation and ajax.
The method checkValidity doesn't solve my problem, because it doesn't show the message error in the UI.
I need to launch the browser validation (and show error messages) using js. To do it I found that I have to submit the form and prevent the event. i.e:
$('form#x').submit(function(e){
e.preventDefault();
// ajax code
});
This works ok and the ajax code is only executed if the all the form fileds are valid. However, I realized that once the form is valid, the ajax code is executed as many times as the submit button was clicked. WTF?
I could solve that issue by using a global flag:
flah = 0;
$form.submit(function(e){
e.preventDefault();
if(flag) return;
flag = 1;
//send x ajax
// in ajax callback >> flag = 0
});
Is there any other way to launch the validation without submit?
Is the event-trigger problem a browser bug or is it a problem in my code?
Thanks

try this:
$('form#x').submit(function(e){
e.preventDefault();
if(!this.checkValidity()){
return false;
}
// ajax code
});

Related

Using Recaptcha with an existing onsubmit handler on the form

I am attempting to integrate Google's reCaptcha v2 invisible on an existing page where the form's onsubmit handler already has a function attached that does the client-side validation. If that function returns true, the form will submit and redirect to another page.
My existing implementation does force the recaptcha validator to appear if it determines you're a bot, but immediately after the form still submits successfully and redirects to the next page.
The expected result is if the client-side validation passes, it should execute the recaptcha and display the recaptcha validator if it's heuristics deem you a bot AND prevent the form from submitting until you pass it's validator.
For reference I am testing the recaptcha via this method: https://stackoverflow.com/a/52036368/2684075
Here's the implementation
<form
class="elq-form"
onsubmit="return handleFormSubmit(this)"
...
>
...
</form>
...
<div
class="g-recaptcha"
data-sitekey="MY_SITEKEY"
data-callback="recaptchaOnSubmit"
data-size="invisible"
>
</div>
<script src="https://www.google.com/recaptcha/api.js" async="" defer=""></script>
<script>
function recaptchaOnSubmit() {
console.log('recaptcha success');
}
(function() {
var form = document.querySelector('.elq-form');
var originalSubmit = form.onsubmit;
form.onsubmit = null;
form.onsubmit = function() {
var isValid = originalSubmit.call(form);
if (isValid) {
window.grecaptcha.execute();
console.log('grecaptcha executed')
}
return isValid;
}
})()
</script>
Are you able to post the contents of handleFormSubmit() function?
I'd suggest using jQuery to handle your event, as it sounds like you're writing on top of an existing project?
The invisible version of the reCAPTCHA is version 3 right? I'm interested, are you displaying version 2, if the reCAPTCHA deems you as a bot via version 3?
$('.elq-form').submit(function () {
// Determine if the reCAPTCHA is successful, ie, use a backend PHP script to validate
if (response == true) {
// return true from the form, therefore, it will proceed
return true;
}
else {
// reCAPTCHA came back as invalid, therefore do not continue.
// We can display an error (paragraph) or anything you like
return false;
}
});
Also may I suggest https://developers.google.com/recaptcha/docs/v3 if you haven't checked it already? As it provides an example for the client side JS to embed.
Hope this helps,

Validate a Form Submit before submitting and writing a result into a field, that will then be submitted - using Prevent default and Ajax requests

When I press the Form Submit button, I want to action some validation (via an Ajax call), and change a screen value, before the Form is actually submitted.
My issue is that when I try this, and I manually action the Submit button, the screen value is not actually updated until the Form has been submitted. Too late!
Is there any way around this issue? I've tried to comment in the code exactly what I mean.
$("form").submit(function (event) {
// we prevent teh default action of the udpate button
event.preventDefault();
alert('In Jquery/JS.. button pressed / Prevented default');
// variables for "self" so we can access the form
// nativley using javascript and not jquery
var self = this,
root = 'https://jsonplaceholder.typicode.com';
// Now call Ajax, get results, and if good, manually call the
// submit button.
$.ajax({
url: root + '/posts/1',
method: 'GET',
success: function (data) {
alert('in ajax success');
}
}).done(function (data) {
alert('in ajax done - Title data = : ' + data.title);
if (data.title !== "") {
// We assign our Input Text field some data
$('#textfield').val(data.title);
// The on screen value actually hasn't updated :o(
alert('about to self submit');
// We go to submit... but our form isn't actually
// updated with the Ajax text yet...
// is that possible before we action the submit???
self.submit();
}
}).fail(function () {
alert('error');
});
});
See JSFiddle : https://jsfiddle.net/dave_pace/890zmj1f/
It is not what you think. JavaScript is single-threaded. Therefore, an alert statement is executed just after its previous statement. It doesn't wait for the previous statement to finish.
Adding to that, alert is quicker than setting the value in the textbox, and it actually blocks the thread until it is dismissed. That's why you cannot see the value set in the textbox, but can see the submit alert first.
Your fiddle is fine, and works as it should. If you want to test this, try to remove all the alert statements from your code, and try to submit your form to an actual URL, for example https://www.google.com.
Though submitting to Google will result in an error, you can actually see that the textbox is being populated before the submit happens.

An error on a form submit allows the submission

I have a form defined in HTML which can be submitted with a submit button.
I also have a jquery handler in which there is a logger on a non existing object.
$("#myform").submit(function() {
console.log(nosuchobject);
return false;
});
With the logger in place, the form is submitted and the browser changes page. But without the logger, the form is not submitted.
My guess is that when there is an error in the logger the returned value is not false. But is it true ? And how come an error allows for a form to be submitted anyway ?
In your logger code you have print a variable instead of string. just update you code with following
$("#myform").submit(function() {
console.log('nosuchobject');
return false;
});
Use preventDefault for preventing form submition:
$("#myform").submit(function(e) {
e.preventDefault();
});
if you get a js error in the submit function the code after the error won't be executed what means that it does not return a false. You can prevent the form submission at the start of your function like this:
$("#myform").submit(function(event) {
event.preventDefault();
// it does not matter if there is an error now.
console.log(nosuchobject);
});
You should still write your code so it runs without errors.

ajax form data pass before the page reloads

I use a jQuery.get() request to send a form data. But often the page reloads/redirects too fast, before my JavaScript/jQuery code catches and sends the form data to where i need. I use alert() to get the ajax request done while the user clicks ok on alert. Now i need the form working as usual (with PHP post and redirect) and to send the form data using jQuery or JavaScript BEFORE the page reloads and NO alerts. Is there any elegant way to make the page wait until jQuery is done with the request (without using alert)?
jQuery('#form').live('submit', function() {
var inputValue = jQuery(this).find('#theInput').val();
jQuery.get('http://someurl.com/order?var=' + inputValue);
//alert('an unwanted alert');
});
UPD: I embed jQuery code through Google Tag Manager's iframe. So I can't change the way the form works. And I shouldn't prevent the form from submitting.
jQuery('#form').live('submit', function(e){
e.preventDefault(); // prevent default behaviour
var inputValue = jQuery(this).find( '#theInput' ).val();
jQuery.get('http://someurl.com/order?var=' + inputValue, function(){
// redirect
});
//alert('an unwanted alert');
});
I would take a look at [done][http://api.jquery.com/deferred.done/] which could probably do what you want it to do. .done() will wait for the entire ajax to finish, and then run whatever function you call within done.
You can bind callback to do redirect and return false; to prevent default redirect shown as below:
jQuery('#form').on('submit', function() {
var inputValue = jQuery(this).find( '#theInput' ).val();
jQuery.get('http://someurl.com/order?var=' + inputValue,
function(data){
//write redirect code here. In case if you want to check response, you can get it in data variable.
});
return false; //prevent default redirect action
});

Preventing form from being submitted with manual validation

I implemented some custom validation logic with JQuery and Unobtrusive validation with help of the following post:
Manually set unobtrusive validation error on a textbox
To save you time reading through that post here is the simple javascript that forces a validation message to be displayed if something fails:
On my textbox .blur():
var errorArray = {};
errorArray["Slug"] = 'Some error message for the Slug text box';
$('#SomeFormId').validate().showErrors(errorArray);
Works great.
My problem is while the failed validation message is displayed, when submit is clicked the form submits just fine.
How can I implement custom validation with code above and prevent the form from being submitted when the message is displayed ? I tired doing something like $('#SomeFormId').valid = false; but it didn't work.
Thank you.
Using $('#SomeFormId') will not work because when you do:
$('#SomeFormId').valid = false;
and then when you access it in your form submit handler again using (what I assume):
var form = $('#SomeFormId'); // or $(this)
if (form.valid) {
//
}
You're essentially creating two different objects, even though they're referring to the same DOM element. So setting valid = true in one will not update it in the second.
The code you gave is very barebones though, so I'm assuming that your validation is separate from your submit handler (since it's in blur anyway), so what you can do is utilize something like .data() or a flag (just make sure that it's in context).
// on blur
$('#SomeFormId').data('isvalid', false); // invalid
// on submit
var isvalid = $('#SomeFormId').data('isvalid');
if (!isvalid) {
// invalid form
ev.preventDefault();
}
EDIT
The jQuery Event object
When you bind a function as an event handler in jQuery, one of the things that jQuery does silently for you is it "creates" a normalized Event object for you. This will contain information about the event you can use in the handler, and also allows you to control the behavior of the event in some ways.
// setting a submit event on my form
// | whatever you put here
// V is the event object.
$('#SomeFormId').on('submit', function (ev) {
// preventing the default action
// : in a form, this prevents the submit
ev.preventDefault();
});
To check if the form is valid, you can use something like this:
var form = $("#SomeFormId");
form.submit(function(event) {
if(form.valid() == false) event.preventDefault();
}
Edited to add a bit more to it, this will take care of your submission/prevention, now you just add in your validation calls.

Categories

Resources