jquery validate firing unhighlight function imediately after highlight - javascript

despite my problem is similar with this
the proposed solution did not work for me.
Let me explain what happens.
As the title suggests unhiglight is called right after highlight.
and this happens only under one scenario only:
using remote method of email.
If the ajax call returns true(after hitting the submit button)(email does not exist) error class is added and immediately replaced by valid class in the fields that are not filled(required)...
if I hit submit again the problem does not appear...if some fields are not filled error class is attached properly.
What differentiates first from second submit(and if email is not changed) is the fact that ajax call for the email is not made.
So if ajax call is made(for the email) and returns true the above problem appears.
The code for the showerrors method found in the above Soverflow post does not help.
I must emphasize that if I remove the remote method for the email the problem is fixed
here is the code inside validate():
$('#bizuserform').validate({
showErrors: function (errorMap, errorList) {
var errors = this.numberOfInvalids();
if (errors) {
var message = errors == 1 ? '1 field is miissing!!!' : errors + ' fields are missing!!!';
$("#error_general span").empty().html(message);
$("#error_general").show();
} else {
$("#error_general").hide();
}
this.defaultShowErrors();
},
highlight: function(element, errorClass, validClass) {
if($(element).attr("id")=='staffclient_yes')
{
$('#staffclient_yes').parent().addClass(errorClass);
}
if($(element).attr("id")=='medical')
{
$('#medical').parent().addClass(errorClass);
}
$(element).addClass(errorClass).removeClass(validClass);
},
unhighlight: function(element, errorClass, validClass) {
if($(element).attr("id")=='staffclient_yes')
{
$('#staffclient_yes').parent().removeClass(errorClass);
}
if($(element).attr("id")=='medical')
{
$('#medical').parent().removeClass(errorClass);
}
$(element).removeClass(errorClass).addClass(validClass);
},
onfocusout: false,
submitHandler: function(form,event) {
event.preventDefault();
//ajax request here...ommited for brevity
},
rules:{
name: {
required: function () {
return $('#coname').is(':blank');
},
normalizer: function( value ) { return $.trim( value );}
},
lastname: {
required: function () {
return $('#coname').is(':blank');
},
normalizer: function( value ) { return $.trim( value );}
},
coname: {
required: function () {
return $('#name,#lastname').is(':blank');
},
normalizer: function( value ) { return $.trim( value );}
},
buztype:{required:true
},
med_spec:{
required: function(element) {return $('#medical').is(':checked');}
},
password:{
required:true,
password:true,
normalizer: function( value ) { return $.trim( value );}
},
address:{ required: true,
normalizer: function( value ) { return $.trim( value );}
},
city:{ required: true,
normalizer: function( value ) { return $.trim( value );}
},
municipality:{ required: true,
normalizer: function( value ) { return $.trim( value );}
},
email:{required: true,
email: true,
remote: {
url: "email_validity.php",//if I remove the remote method here problem is fixed
type: "post"
},
normalizer: function( value ) { return $.trim( value );}
},
phone:{required:true,
normalizer: function( value ) { return $.trim( value );},
digits: true,
rangelength: [10, 14]
},
staff_to_client:{
required: "#staf_eng:visible"
}
},
messages:{
buztype:'',
staff_to_client:'',
med_spec:'',
coname:"",
name:'',
lastname:'',
password:{required:""
},
address:'',
city:'',
municipality:'',
email:{required:"",
email:'not valid email',
remote:'email allready exists.'
},
phone:{required:"",
rangelength:'phonenumber messasge.',
digits:'only digits here'
},
staff_to_client:{
required: ""
}
}
});

Related

How change JQuery Validation Message without refreshing website [duplicate]

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
},

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

kflorence jquery-wizard: branch validation

I'm using the kflorence jquery wizard: https://github.com/kflorence/jquery-wizard/ and I ran into an issue with validation when using branching.
I'd like to have the wizard show an error message instead of the defaulted "alert" when the selected option is blank. It currently works for regular steps, but when I get to a branched question, the validation does not work.
<script type="text/javascript">
jQuery(function($) {
$("#example-3" ).wizard({
transitions: {
q3: function( state, action ) {
var branch = state.step.find( "[name=q3]:selected" ).attr("class");
if (!branch ) {
????
}
return branch;
},
q5: function( state, action ) {
var branch = state.step.find( "[name=q5]:selected" ).attr("class");
if ( !branch ) {
//alert( "Please select a value to continue." );
}
return branch;
},
q6: function( state, action ) {
var branch = state.step.find( "[name=q6]:selected" ).attr("class");
if ( !branch ) {
//alert( "Please select a value to continue." );
}
return branch;
},
q7: function( state, action ) {
var branch = state.step.find( "[name=q7]:selected" ).attr("class");
if ( !branch ) {
//alert( "Please select a value to continue." );
}
return branch;
},
q8: function( state, action ) {
var branch = state.step.find( "[name=q8]:selected" ).attr("class");
if ( !branch ) {
//alert( "Please select a value to continue." );
}
return branch;
}
},
beforeForward: function( event, state ) {
return !!$( this ).wizard( "form" ).valid();
},
afterSelect: function( event, state ) {
//$( "#progressbar2" ).progressbar( "value", state.percentComplete );
$( "#location2" ).text(Math.round(state.percentComplete) + "%");
if($('#unqualified').is(':visible')) {
$(".pad").hide();
} else {
$(".pad").show();
};
}
}).validate({
rules :{
q1: {
required: true
},
q2: {
required: true
},
q3: {
required: true
},
q4: {
required: true
},
q5: {
required: true
},
q6: {
required: true
},
q7: {
required: true
},
q8: {
required: true
}
}
});
});
</script>
I need the validation error to fire if the branch returns false.
I got it to work using:
if (!branch) {
$("form").valid();
}

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

jquery validate with if statement in custom method

I am using the validate plugin for jquery and have the following custom method:
$.validator.addMethod("username", function(value, element) {
if (element.prop("required")) {
var re = new RegExp('^([FG]?\\d{5}|\\d{5}[AB])$');
} else {
var re = new RegExp('^'+element.defaultValue+'|^([FG]?\\d{5}|\\d{5}[AB])$');
}
return re.test(value);
});
The if statement returns the error element.prop is not a function.
I've also tried $(this).prop... and although I don't get any errors it always runs the else part of the statement.
Is there anything else I can use instead to achieve this??
EDIT:
Here's the call:
$("#myform").validate({
debug: true,
ignore: ".ignore",
rules: {
field: {
required: {
depends: function() {
return $(this).prop("required");
}
},
username: true,
}
},
messages: {
field: {
username: "Enter a valid username"
}
},
success: function(label) {
label.text("Good result!");
},
submitHandler: function() {
alert("submitted!");
}
});
I think you should use:
if ($(element).prop("required")) {
you may be using older jQuery version:
try $(element).attr("required")

Categories

Resources