Jquery Validation From Another Function - javascript

I am using the http://jqueryvalidation.org/ to validate my forms and by default this is called when the form gets submitted. I am wanting to start the validation when the function I have wrapped it into is called.
So basically, I have this for the validation:
function ticketCreateSubmit()
{
$("#ticketForm").validate({
...
});
}
And then this is getting called by: ticketCreateSubmit(); in my payments page. The form does have the id of ticketForm. The function does get called, but the validation does not take action?
I searched the validation website and I found that if I put onsubmit: false, it doesn't process it on form submit, but that still didn't get the validation to run when the function is being called?
How would I go about this?
Just so everyone understands, I'm only needing to call the VALIDATION so it runs from the external script. I'm not needing to do anything else. Just execute the validation.

Try this
var form = $("#ticketForm")
form.validate({
...
});
function ticketCreateSubmit()
{
form.valid()
}

You could try putting onsubmit="ticketCreateSubmit();return false" on the form submit.

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,

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.

What is the proper way to submit HTML form after asynchronous data load?

Silly that I can't find this so I apologize in advance if I have duplicated, but I have looked through search engines and SO without finding what I need.
What is the proper way to submit an HTML form upon user click but only after I have asynchronously loaded data from a 3rd party API to fill in for some of the form's hidden fields?
I tried this structure, which has not worked:
form onclick = function1()
function1() calls function apicall that retrieves info from 3rd party api and in its completion handler then calls function2
function2 checks all form fields and returns true if form should be submitted, false if it should not
With this structure, my form is always submitted, although both the 3rd party api function completion handler and function2 are working properly on their own. function2 can return false all day long but the form still submits. What can I do about this? The asychronous timing seems alright but somehow the return false is not getting back to the FORM element.
Thank you for any tips or code samples.
Asynchronous functions can't return anything -- the caller isn't waiting for them to finish. So the form's onsubmit handler should return false to prevent the form from submitting.
Then in function2(), if the form validation succeeds, it can call
document.getElementById('formID').submit();
to perform the actual form submission.

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.

Launch browser's validation and error messages without submit

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
});

Categories

Resources