Prevent hubspot form submission - jQuery validation - javascript

I would like to prevent submission if form is not valid and to print some error message if possible, here's what I have so far:
btw "link to the current page" is defined in php
hbspt.forms.create({
css: '',
portalId: 'hs-portal-id-goes-here',
formId: 'hs-form-id-goes-here',
onFormReady: function(){
jQuery('#hsForm_hs-form-id-goes-here').validate({
errorPlacement: function(error, element) {},
rules: {
firstname: { required: true },
lastname: { required: true },
email: { required: true },
message: { required: true }
},
submitHandler: function(form, e) {
e.preventDefault();
window.open('link to the current page', '_self');
form.submit();
jQuery(newForm)
var newForm = jQuery('#hsForm_hs-form-id-goes-here');
window.setTimeout(function() {
newForm.html('<h3>Thank you for submitting the form</h3>');
}, 1000);
}
});
}
});

Do you want client-side or server-side validation?
If answer is client-side, you should do it with javascript, check inputs and write validation messages.
If it is server-side, you should consider using ajax, serialize your form, send it to server, and react depending on answer (was data successfully validated, or not)

Related

How to use jQuery validator and AJAX request at the same time?

I'm using jQuery Validation Plugin.
I'm trying to submit my login page using AJAX but at the same time I'm also trying to validate the form using jQuery Validate; However when I submit it I only validates the last field after the AJAX request has been submitted; therefore no validation is taking place.
I'm trying to get the form's submit button to be disabled until validation has passed. Then allow the AJAX request to take place once validated it will undisable the button; allowing the user to submit the form using enter or clicking the button. However it doesn't seem to be working.
$(document).ready(function() {
$("#signin").validate({
rules: {
username: {
required: true
},
password: {
required: true,
minlength: 8,
maxlength: 50
}
},
messages: {
username: {
required: "Your username is required."
},
password: {
required: "Your password is required.",
minlength: "Passwords are between 8-50 characters.",
maxlength: "Passwords are between 8-50 characters."
}
}
});
$("form .login").click(function () {
$.ajax(/* ... */);
return false;
});
});
Instead of using click event listener on submit button, use submit event on form. Also you need to check if the form is valid using .valid() method on it:
$("form").submit(function() {
if (!$("form").valid()) return;
var username = $("form #username").val();
var password = $("form #password").val();
// ...
});

POST information to 2 areas. PHP / Javascript

Just wondering if you can try and assist.
I have a register form in WordPress that is being posted to a user database. I also need to pass the same form information to a webhook (Zapier).
I understand you cannot have 2 form action's for one form however I ideally need to find the best way of submitting both sets of information; one to the database and one to the webhook link.
An example of my code posting to my database. I need this to also post to
https://zapier.com/examplehook/
<form name="register_form" id="register_form<?php $template->the_instance(); ?>" action="$template->the_action_url( 'save-register' ); ?>" method="post”>
I was thinking of possibly using an onclick event to run a javascript function that also does a simultaneous form action. I'm confused if that would work though.
//edited code
$('#registerform').validate({ // initialize the plugin
rules: {
first_name: {
required: true
},
last_name: {
required: true
},
user_email: {
required: true,
email: true
},
user_login: {
required: true
},
hear_about_us: {
required: true
},
contact_number: {
required: true
},
address:{
required: true
},
post_code: {
required: true
}
},
submitHandler: function (form) {
$('#registerform').on('submit', function(event) {
event.preventDefault();
var xhr1 = $(this).ajaxSubmit({url: 'https://zapier.com/example-hook/'}).data('jqxhr');
var xhr2 = $(this).ajaxSubmit({url: '/register/'}).data('jqxhr');
$.when(xhr1, xhr2).then(function() {
window.location.replace("/register-step2/");
}, function() {
// error occured
});
});
}
});
Any suggestions would be ideal!
Thanks
You can use Jquery Form Plugin for this:
$('form').on('submit', function(event) {
event.preventDefault();
var xhr1 = $(this).ajaxSubmit({url: 'http://firsturl'}).data('jqxhr');
var xhr2 = $(this).ajaxSubmit({url: 'http://secondurl'}).data('jqxhr');
$.when(xhr1, xhr2).then(function() {
// both submits succeeded, redirect
}, function() {
// error occured
});
});

if statement inside jQuery Validation plugin remote rule

I have two forms: one for adding a new user and the other for user data modification.
Forms are basically the same, only difference is that when doing modification username field should not be checked if exists in database.
In Js file I do field validations. One of those validations is checking if username already exists in database. In modification this should not be considered.
This is why I thought this, but it's not working:
I differentiate the two forms with div id.
(view snippet add_user form):
<div id="add_user">
<form action="{site_url()}admin/updateFrontUser" id="form_sample_2" class="form-horizontal" method="post">
(view snippet edit_user form):
<div id="edit_user">
<form action="{site_url()}admin/updateFrontUser" id="form_sample_2" class="form-horizontal" method="post">
and then:
(js file snippet)
var algo = $('.add_user', form2);
form2.validate({
errorElement: 'span', //default input error message container
errorClass: 'help-inline', // default input error message class
focusInvalid: false, // do not focus the last invalid input
ignore: "",
rules: {
username: {
required: true,
minlength: 2,
maxlength: 15,
pattern: "[A-z](([\._\-][A-z0-9])|[A-z0-9])*[a-z0-9_]*",
remote: {
data: function(){
if (algo) {
url: '/admin/checkUsername';
type: 'POST';
};
}
}
},
The remote rule it's supposed to check if username exists. That function is already built in my admin.php. It worked previously, before I made the modifications I mentioned.
So to resume, How do I do just to use remote rule only for a new user (I mean, when using add form) ?
Please Try below rule
$().ready(function() {
$("#id_frm").validate({
rules: {
"id_question": {
required: true
},
"id_number": {
required: function(){ return $('input:radio[name=id_question]:checked').val() == 'Yes' },
minlength: 10,
minlength: 10
},
"contact_method": {
required: function(){ return $('input:radio[name=id_question]:checked').val() == 'No' }
}
},
messages: {
"id_question": {
required: "Please choose if you have an ID or not."
},
"id_number": {
required: "Please Enter ID."
},
"contact_method": {
required: "Please choose a contact method."
}
},
});
});

Suddenly my form submit button only works after having being clicked twice

I'm not sure why. I think it started when I incorportated jQuery's .validator.
The website: http://friendswithwheels.herokuapp.com
The javascript:
$('#newLender').validate({
rules: {
fee: {
required: true,
number: true,
},
email: {
required: true,
isYaleEmailAddress: true,
}
},
errorPlacement: function (error , element) {
error.addClass("errorMessage");
error.insertAfter(element);
},
submitHandler: function (form) {
$('#newLender').submit( ajaxPostForLenders ); //ajaxPostForLenders submits the request
}
});
This question here will answer your question:
Need to press submit twice for submitting a form with ajax (jquery validation plugin)
I am not going to copy and paste their answer as it's their work. But, feel free to accept my answer.
Cheers
Matt

How can I detect when jQuery Validation is done, and call something based on that event?

I'm new to jQuery.
Working with jQuery validation plugin & cufon at the same time is giving me really hard time.
Basically, I want to detect event once jQuery Validation did what it had to do and call Cufon.refresh() straight after it.
$('#commentForm').validate({
rules: {
password: {
required: true,
minlength: 8,
maxlength: 8,
number: true
},
}
});
We are expecting <label class="error"> SOME TEXT </label> when form is not valid.
And once that created I want to Cufon.refresh() on that label created by jQuery Validation.
How can I detect when jQuery Validation is done, and call something based on that event?
Any help much appreciated.
Regards,
Piotr
Thanks to #Ariel - if there is a 'success' there has to be a 'not-success' as well, so..
Working code:
$('#commentForm').validate({
rules: {
password: {
required: true,
minlength: 8,
maxlength: 8,
number: true
}
},
showErrors: function(errorMap, errorList) {
this.defaultShowErrors();
Cufon.refresh();
//alert('not valid!')
},
success: function() {
//alert('valid!')
}
});
Thanks again for the idea!
Use the success option:
$('#commentForm').validate({
rules: {
password: {
required: true,
minlength: 8,
maxlength: 8,
number: true
},
}
success: function() { .... }
});
Note that you have an extra comma after the close brace for the password object. This will give an error in IE.
<script src="js/validate/jquery-1.11.1.min.js"></script>
<script src="js/validate/jquery.validate.min.js"></script>
<script src="js/validate/additional-methods.min.js"></script>
<script>
jQuery.validator.setDefaults({
success: "valid"
});
var form = $("#myform");
form.validate({
rules: {
name: {required: true, minlength: 2},
lastname: {required: true, minlength: 2}
}
});
$("#button").click(function() {
if(form.valid() == true ) { // here you check if validation returned true or false
$("body").addClass("loading");
}
})
</script>
submitHandler: { function(){ bla bla }}
This will allow you to execute code upon the completion of the validate. you will need to place a submit form snippet though, since it replaces the default handler.
EDIT:
// specifying a submitHandler prevents the default submit
submitHandler: function() {
alert("submitted!");
},
// set this class to error-labels to indicate valid fields
success: function(label) {
// set as text for IE
label.html(" ").addClass("checked");
}
You can use either to do what you want. submitHandler allows you to stop the submit and execute code instead ( you can possibly use it to perform code BEFORE you submit it ) or success to execute code after the submit.
Put it inside the errorPlacement option.
errorPlacement: function(error, element) {
error.appendTo( element.parent() );
yourCodeHere();
}
$(document).ready(function() {
$('#commentForm').submit(function(){
var validationResponse = $('#commentForm').valid();
if(validationResponse) {
// when true, your logic
} else {
// when false, your logic
return false;
}
});
$("#commentForm" ).validate({
rules: {
"first_name": {
required: true
}
},
messages: {
"first_name": {
required: "First Name can not be empty"
}
}
});
});

Categories