How change JQuery Validation Message without refreshing website [duplicate] - javascript

This question already has answers here:
jquery .validate() variable error message
(3 answers)
Closed 1 year ago.
I am using jQuery Validation from here: https://jqueryvalidation.org. Currently, I have two types of Messages prepared. They are popping out. When I'm changing language on web variables global variable with messages also is changing, but message in validator don't. Language of the validator change after I refresh the website. How can I change it on live without refreshing the website?
HTML is no needed, because everything is happening in JS file.
This is a function that are changing values in the object.
JS:
function setLang(lang) {
(lang) ? lang: "pol";
if (lang == "pol") {
Messages = {
formFirstnameRequired: 'Pole imie jest wymagane!',
formLastnameRequired: 'Pole nazwisko jest wymangane!',
formEmailRequired: 'Pole email jest wymagane!',
formTitleRequired: 'Pole Tytuł jest wymagane!',
formMessageRequired: 'Pole wiadomość jest wymagane!',
}
} else if (lang == "eng") {
Messages = {
formFirstnameRequired: 'Field firstname is required!',
formLastnameRequired: 'Field lastname is required!',
formEmailRequired: 'Field email is required!',
formTitleRequired: 'Field title is required!',
formMessageRequired: 'Field message is required!',
}
}
}
I'm also using this cookie for managing the language of this form validation:
if (getCookie("lang") == null) {
document.cookie = 'lang=pol';
}
setLang(getCookie("lang"));
$(".nav").on("click", "#polLang", (event) => {
document.cookie = 'lang=pol';
setLang(getCookie("lang"));
});
$(".nav").on("click", "#engLang", (event) => {
document.cookie = 'lang=eng';
setLang(getCookie("lang"));
});
Here I have validation
JS:
$("#contactForm").validate({
rules: {
"formFirstname": {
required: true,
},
"formLastname": {
required: true,
},
"formEmail": {
required: true,
},
"formTitle": {
required: true,
},
"formMessage": {
required: true,
}
},
messages: {
"formFirstname": {
required: Messages.formFirstnameRequired,
string: true
},
"formLastname": {
required: Messages.formLastnameRequired,
string: true
},
"formEmail": {
required: Messages.formEmailRequired,
email: true,
},
"formTitle": {
required: Messages.formTitleRequired,
string: true
},
"formMessage": {
required: Messages.formMessageRequired,
string: true
}
},
onfocusout: false,
errorPlacement: function(error) {
toastr.error(error);
},
submitHandler: function(form) {
toastr.success('success')
return false;
},
invalidHandler: function() {
return;
}
});

Jquery validator msgs are static. If you want to update them dynamically you can create a function, that will return a new msg.
Like this:
"formFirstname": {
required: function getFormFirstname() { return Messages.formFirstnameRequired },
string: true
},

Related

validating that a canvas has been drawn in

I'm implementing an online waiver where a client has to sign into canvas before they can complete the form. I use Signature_Pad from szimek and jquery-validate and would like to have the canvas (which is part of the form) be included. I tried a custom formatter, like so:
let wrapper = document.getElementById("signature_pad");
var signaturePad = new SignaturePad(wrapper.querySelector("canvas"), {
backgroundColor: 'white'
});
jQuery.validator.addMethod("checkSignature", function(value, element) {
return signaturePad.isEmpty() == false;
}, "Signature must be provided");
$("form[name='form-waiver']").validate({
rules: {
WaiverName: {
required: true,
minlength: 2
},
signature_pad: {
checkSignature: true
}
},
messages: {
WaiverName: "The name has to be filled out"
},
successClass: "valid",
errorClass: "invalid",
submitHandler: function (form) {
...
}
};
However, the form validates even if the canvas is empty. Is there a method to include the canvas in the form validation?

Submit form data without javascript

TL;DR
How to make a form to make a normal post instead of making a submission via JQuery?
I bought a theme recently and I'm making a form with several steps. I'm using the "Wizard" component of this theme and you can see how it works through this link:
https://keenthemes.com/metronic/preview/demo1/custom/pages/wizard/wizard-2.html
My problem is with the submission of this form. I would like to make a common submission. As it stands, the form must be submitted using JQuery.
I made some changes to my form to be able to make a common submission. For example:
I informed the POST method and an action for the form:
<form class="m-form m-form--label-align-right- m-form--state-" id="m_form" action="sale/new" method="post" enctype="multipart/form-data">
And I also created a "Submit" button:
<button type="submit" class="btn btn-primary" data-wizard-action="submit">Save</button>
For the Wizard work, the form must have an id (m_form) and the submit button must also have the attribute data-wizard-action="submit".
I am using the javascript of the theme itself, and it is precisely because I don't know much about JS that I believe I am facing problems. I tried to remove the e.preventDefault, but the form still does not POST to the action I determined. The javascript code for the theme I'm using is this:
//== Class definition
var WizardDemo = function () {
//== Base elements
var wizardEl = $('#m_wizard');
var formEl = $('#m_form');
var validator;
var wizard;
//== Private functions
var initWizard = function () {
//== Initialize form wizard
wizard = new mWizard('m_wizard', {
startStep: 1
});
//== Validation before going to next page
wizard.on('beforeNext', function(wizardObj) {
if (validator.form() !== true) {
wizardObj.stop(); // don't go to the next step
}
})
//== Change event
wizard.on('change', function(wizard) {
mUtil.scrollTop();
});
//== Change event
wizard.on('change', function(wizard) {
if (wizard.getStep() === 1) {
// alert(1);
}
});
}
var initValidation = function() {
validator = formEl.validate({
//== Validate only visible fields
ignore: ":hidden",
//== Validation rules
rules: {
//=== Client Information(step 1)
//== Client details
name: {
required: true
},
email: {
required: true,
email: true
},
phone: {
required: true,
phoneUS: true
},
//== Mailing address
address1: {
required: true
},
city: {
required: true
},
state: {
required: true
},
city: {
required: true
},
country: {
required: true
},
//=== Client Information(step 2)
//== Account Details
account_url: {
required: true,
url: true
},
account_username: {
required: true,
minlength: 4
},
account_password: {
required: true,
minlength: 6
},
//== Client Settings
account_group: {
required: true
},
'account_communication[]': {
required: true
},
//=== Client Information(step 3)
//== Billing Information
billing_card_name: {
required: true
},
billing_card_number: {
required: true,
creditcard: true
},
billing_card_exp_month: {
required: true
},
billing_card_exp_year: {
required: true
},
billing_card_cvv: {
required: true,
minlength: 2,
maxlength: 3
},
//== Billing Address
billing_address_1: {
required: true
},
billing_address_2: {
},
billing_city: {
required: true
},
billing_state: {
required: true
},
billing_zip: {
required: true,
number: true
},
billing_delivery: {
required: true
},
//=== Confirmation(step 4)
accept: {
required: true
}
},
//== Validation messages
messages: {
'account_communication[]': {
required: 'You must select at least one communication option'
},
accept: {
required: "You must accept the Terms and Conditions agreement!"
}
},
//== Display error
invalidHandler: function(event, validator) {
mUtil.scrollTop();
swal({
"title": "",
"text": "There are some errors in your submission. Please correct them.",
"type": "error",
"confirmButtonClass": "btn btn-secondary m-btn m-btn--wide"
});
},
//== Submit valid form
submitHandler: function (form) {
}
});
}
var initSubmit = function() {
var btn = formEl.find('[data-wizard-action="submit"]');
btn.on('click', function(e) {
e.preventDefault();
if (validator.form()) {
//== See: src\js\framework\base\app.js
mApp.progress(btn);
//mApp.block(formEl);
//== See: http://malsup.com/jquery/form/#ajaxSubmit
formEl.ajaxSubmit({
success: function() {
mApp.unprogress(btn);
//mApp.unblock(formEl);
swal({
"title": "",
"text": "The application has been successfully submitted!",
"type": "success",
"confirmButtonClass": "btn btn-secondary m-btn m-btn--wide"
});
}
});
}
});
}
return {
// public functions
init: function() {
wizardEl = $('#m_wizard');
formEl = $('#m_form');
initWizard();
initValidation();
initSubmit();
}
};
}();
jQuery(document).ready(function() {
WizardDemo.init();
});
I would like to know if there is any way to keep the Wizard and the validation working, but in a way that it is possible to make a common submission for the action that I defined for the form.
You just need a slight change in your initSubmit() function.
var initSubmit = function() {
var btn = formEl.find('[data-wizard-action="submit"]');
btn.on('click', function(e) {
e.preventDefault();
if (validator.form()) {
//== See: src\js\framework\base\app.js
mApp.progress(btn);
//mApp.block(formEl);
//== See: http://malsup.com/jquery/form/#ajaxSubmit
/*
formEl.ajaxSubmit({
success: function() {
mApp.unprogress(btn);
//mApp.unblock(formEl);
swal({
"title": "",
"text": "The application has been successfully submitted!",
"type": "success",
"confirmButtonClass": "btn btn-secondary m-btn m-btn--wide"
});
}
});
*/
// Use this one instead:
formEl.submit();
}
});
}
This simply means that:
Instead of doing an AJAX request if validation result is positive, just do a normal submission.
Here's the reference for the submit() method of jQuery:
https://api.jquery.com/submit/
By the way, this question can be found under the title (how to submit form using jQuery ?), see this question for example:
Submit a form using jQuery

Assign dynamically loaded html element to variable

I'm trying to validate fields loaded using jQuery $().load();.
with jquery validation plugin (jqueryvalidation.org)
My code is:
var contactForm = $('#contact-form');
contactForm.validate({
rules: {
name: {
required: true,
},
email: {
required: true,
email: true
},
phone: {
required: false,
phoneUS: true
},
message: {
required: true
}
}
});
Unfortunately it doesn't work with elements loaded with load();
After some google searching I found some solution but they all are aimed on "events", not to pass dynamically added input to variable:
$(document).on('click','#submit',function() {});
I also tried to approach it with this code bellow :
$('.home').click(function() {
$("#article").load("./ #article > *",function(){
contactForm = $(this).find("#contact-form");
});
Also doesn't work though :(
I will appreciate any clues and help.
Try to add them dynamically :
$("#contact-form").find('input').each(function () {
$(this).rules("add", {
required: true
});
});
Hope this helps.

Submit handler is working but its very slow

Hello guys I am submitting my form using submit handler and its working but its very slow. Please help me to make it fast. Thanks in advance
Following is my javascript code for login form......
var handleLoginForm = function () {
$('.login-form').validate({
errorElement: 'label', //default input error message container
errorClass: 'help-inline', // default input error message class
focusInvalid: false, // do not focus the last invalid input
rules: {
username: {
required: true
},
password: {
required: true
},
user_type: {
required: true
},
remember: {
required: false
}
},
messages: {
username: {
required: "Username is required."
},
password: {
required: "Password is required."
},
user_type: {
required: "User Type is Required."
}
},
invalidHandler: function (event, validator) { //display error alert on form submit
$('.alert-error', $('.login-form')).show();
},
highlight: function (element) { // hightlight error inputs
$(element)
.closest('.control-group').addClass('error'); // set error class to the control group
},
data: $('#form_modulesadd').serialize(),
success: function (label) {
label.closest('.control-group').removeClass('error');
label.remove();
},
errorPlacement: function (error, element) {
error.addClass('help-small no-left-padding').insertAfter(element.closest('.input-icon'));
},
submitHandler: function (form) {
$( ".login-form input" ).submit();
window.location.href = "check.php";
}
});
It was fast when i was submitting the form using php but I must have to use javascript to submit this form......
Run the JS when the form is submitted:
$(".login-form").submit(function(){
$('.login-form').validate({
errorElement: 'label', //default input error message container
errorClass: 'help-inline', // default input error message class
focusInvalid: false, // do not focus the last invalid input
rules: {
username: {
required: true
},
password: {
required: true
},
user_type: {
required: true
},
remember: {
required: false
}
},
messages: {
username: {
required: "Username is required."
},
password: {
required: "Password is required."
},
user_type: {
required: "User Type is Required."
}
},
invalidHandler: function (event, validator) { //display error alert on form submit
$('.alert-error', $('.login-form')).show();
},
highlight: function (element) { // hightlight error inputs
$(element)
.closest('.control-group').addClass('error'); // set error class to the control group
},
data: $('#form_modulesadd').serialize(),
success: function (label) {
label.closest('.control-group').removeClass('error');
label.remove();
},
errorPlacement: function (error, element) {
error.addClass('help-small no-left-padding').insertAfter(element.closest('.input-icon'));
},
submitHandler: function (form) {
$( ".login-form input" ).submit();
window.location.href = "check.php";
}
});
});
This keeps the JS from running until the form is submitted.
UPDATE:
$(".login_form").submit(function(){
$(this).validate({ ... });
});
Not sure if this will work, but the repeated selector seemed a bit awkward to me.
I solved the same problem by changing the implementation of submitHandler like below. I just take the first item [0] of the forms selector.
submitHandler: function (form) {
$(".login-form input")[0].submit();
...
}

How can I get a message to appear when I submit a form using Happy.js?

I tried to include a conditional in the unHappy function; While the form processes, I don't get the message indicating success! Here's my code.
var dd= $.noConflict();
dd(document).ready(function () {
dd('.success').hide();
dd('#frmContact').isHappy({
fields: {
// reference the field you're talking about, probably by `id`
// but you could certainly do $('[name=name]') as well.
'#yourName': {
required: true,
message: 'Might we inquire your name'
},
'#email': {
required: true,
message: 'How are we to reach you sans email??',
test: happy.email // this can be *any* function that returns true or false
},
'#comments': {
required: true,
message: 'Please leave a message!',
}
},
unHappy: function () {
var yourName = dd('#yourName').val();
var email = dd('#email').val();
var comments = dd('#comments').val();
if (yourName && email && comments == true){
dd('.success').show();
return;
}
},
});
});

Categories

Resources