jQuery validation - callback method only for fields that fail validation - javascript

Example: http://jqueryvalidation.org/files/demo/custom-methods-demo.html.
The code:
validate({
errorPlacement: function(error, element) {
error.appendTo( element.parent("td").next("td") );
},
rules: {
number: {
required:true,
minlength:3,
maxlength:15,
number:true
},
secret: "buga",
math: {
equal: 11
}
}
});
Question:
Is there a method that will ONLY fire if a field being validated actually fails to validate? errorPlacement above fires for every fields, regardless of validation result.
Thanks.

Here's what worked for me:
$('#invite').validate({
invalidHandler: function(event, validator) {
if (validator.numberOfInvalids()) {
for (i in validator.errorList) {
error = validator.errorList[i];
if (typeof error['element'] === 'object') {
fGrp = $(error['element']).closest('.form-group');
fGrp.toggleClass('has-error', true);
fGrp.find('.validationErrorMessage').html(error.message).toggleClass('nodisplay', false);
}
}
}
},
errorPlacement: function(error, element) { // Do nothing
},
rules: {
email: {
required: true,
email: true,
remote: {
url: '/admin/isgmail/',
type: 'POST',
dataType: 'json',
data: {
email: function() {
return $('#email').val();
}
}
}
},
},
onkeyup: false,
onfocusout: false
});

Related

Change validation requirements in contact form

What to change in the code below (.js from contact form) so that "nazwisko" field is not a required field? This is one file from .php contact form. I was checking some options but I`m not so familiar with .js. Is it enough to just erase this "nazwisko" line from the code or should I just put "false" next to the requirements?
Thank you for your support!
$(document).ready(function(){
/***************************************/
/* Form validation */
/***************************************/
$( '#j-forms' ).validate({
/* #validation states + elements */
errorClass: 'error-view',
validClass: 'success-view',
errorElement: 'span',
onkeyup: false,
onclick: false,
/* #validation rules */
rules: {
nazwisko: {
required: true
},
dataur: {
required: true
},
email: {
required: true,
email: true
},
'imiona-rodzice': {
required: true
},
telefon: {
required: true
},
klasa: {
required: true
},
szkola: {
required: true
},
adres: {
required: true
},
telkur: {
required: true
}
},
messages: {
nazwisko: {
required: 'Podaj swoje Imię i Nazwisko'
},
dataur: {
required: 'Podaj swoją datę urodzenia'
},
'imiona-rodzice': {
required: 'Podaj imiona rodziców'
},
telefon: {
required: 'Podaj telefon do rodziców'
},
klasa: {
required: 'Podaj swoją klasę'
},
szkola: {
required: 'Podaj swoją szkołę'
},
adres: {
required: 'Podaj swój adres'
},
telkur: {
required: 'Podaj swój telefon'
},
email: {
required: 'Podaj adres email',
email: 'Niepoprawny format'
},
},
// Add class 'error-view'
highlight: function(element, errorClass, validClass) {
$(element).closest('.input').removeClass(validClass).addClass(errorClass);
if ( $(element).is(':checkbox') || $(element).is(':radio') ) {
$(element).closest('.check').removeClass(validClass).addClass(errorClass);
}
},
// Add class 'success-view'
unhighlight: function(element, errorClass, validClass) {
$(element).closest('.input').removeClass(errorClass).addClass(validClass);
if ( $(element).is(':checkbox') || $(element).is(':radio') ) {
$(element).closest('.check').removeClass(errorClass).addClass(validClass);
}
},
// Error placement
errorPlacement: function(error, element) {
if ( $(element).is(':checkbox') || $(element).is(':radio') ) {
$(element).closest('.check').append(error);
} else {
$(element).closest('.unit').append(error);
}
},
// Submit the form
submitHandler:function() {
$( '#j-forms' ).ajaxSubmit({
// Server response placement
target:'#j-forms #response',
// If error occurs
error:function(xhr) {
$('#j-forms #response').html('An error occured: ' + xhr.status + ' - ' + xhr.statusText);
},
// Before submiting the form
beforeSubmit:function(){
// Add class 'processing' to the submit button
$('#j-forms button[type="submit"]').attr('disabled', true).addClass('processing');
},
// If success occurs
success:function(){
// Remove class 'processing'
$('#j-forms button[type="submit"]').attr('disabled', false).removeClass('processing');
// If response from the server is a 'success-message'
if ( $('#j-forms .success-message').length ) {
// Remove classes 'error-view' and 'success-view'
$('#j-forms .input').removeClass('success-view error-view');
$('#j-forms .check').removeClass('success-view error-view');
// Reset form
$('#j-forms').resetForm();
// Prevent submitting the form while success message is shown
$('#j-forms button[type="submit"]').attr('disabled', true);
setTimeout(function(){
// Delete success message after 5 seconds
$('#j-forms #response').removeClass('success-message').html('');
// Make submit button available
$('#j-forms button[type="submit"]').attr('disabled', false);
}, 5000);
}
}
});
}
});
/***************************************/
/* end form validation */
/***************************************/
as #Amit said:
Only change this one line in rules section.
Not necessary to change or delete the message in message part itself.
/* #validation rules */
rules: {
nazwisko: {
required: false
},

Form submit inside Ajax JQuery

I have to submit a form inside the Ajax.
I'm receiving 'form.submit is not a function' JQuery error.
$("#form").validate({
// Specify the validation rules
rules: {
type: "required",
groups: {
required: true
}
},
// Specify the validation error messages
messages: {
type: "Type is required",
groups: {
required: "Group is required"
}
},
submitHandler: function(form) {
$.ajax({
type: "POST",
url: "check_exists.php",
data: {
groups: $( "#groups" ).val(),
type: $( "#type" ).val()
},
success: function(data) {
if(data == "true") {
form.submit(); // It shows form.submit is not a function
} else {
// Displays error
}
}
});
}
});
When I give the form.submit() function above the Ajax, It works!
Then how do I submit this form inside the Ajax success function?
Hey u can use the arrow function feature here
$("#form").validate({
// Specify the validation rules
rules: {
type: "required",
groups: {
required: true
}
},
// Specify the validation error messages
messages: {
type: "Type is required",
groups: {
required: "Group is required"
}
},
submitHandler: function(form) {
$.ajax({
type: "POST",
url: "check_exists.php",
data: {
groups: $( "#groups" ).val(),
type: $( "#type" ).val()
},
success: (data) => {
if(data == "true") {
form.submit();
} else {
// Displays error
}
}
});
}
});
It will bind the context of the callback function to submitHandler function
try changing the scope of the form variable:
var form_to_be_submitted = null;
$("#form").validate({
// Specify the validation rules
rules: {
type: "required",
groups: {
required: true
}
},
// Specify the validation error messages
messages: {
type: "Type is required",
groups: {
required: "Group is required"
}
},
submitHandler: function(form) {
form_to_be_submitted = form;
$.ajax({
type: "POST",
url: "check_exists.php",
data: {
groups: $( "#groups" ).val(),
type: $( "#type" ).val()
},
success: function(data) {
if(data == "true") {
form_to_be_submitted.submit(); // It shows form.submit is not a function
} else {
// Displays error
}
}
});
}
});

How to make Ajax call after successfully filled the form fields

Here I am using jQuery validation. It is working fine, after fill all form fields I want do Ajax call but I am not able to do that. I am getting error. How can I do?
jQuery(document).ready(function(){
jQuery("#SubmitForm").validate({
rules: {
"address": {
required: true
},
"username": {
required: true
},
"mobileNumber": {
required: true,
number: true,
minlength : 12
},
"userEmailid": {
required: true,
email: true
},
"message": {
required: true
}
},
messages: {
"address": {
required: "Please enter your Location."
},
"username": {
required: "Please enter your Fullname."
},
"mobileNumber": {
required: "Please enter your Mobile Number."
},
"userEmailid": {
required: "Please enter your Email.",
email: "Please enter valid Email."
},
"message": {
required: "Please enter Message."
}
},
/* jQuery.ajax({
type:'POST',
url :"php/submit_hitachiForm.php",
data: jQuery('form#SubmitForm').serialize(),
cache: false,
contentType: false,
processData: false,
success: function(data) {
console.log(data);
if(data == "success"){
$("#success_message").show();
$("#success_message").fadeOut(4000);
}
},
error:function(exception){
alert('Exeption:'+exception);
}
}); */
});
});
Put all the validation:
$('#SubmitForm).validate({
// validation rules
});
and after that initialize the validation function like:
if($('#SubmitForm).valid())
{
// make ajax() call here
}
Try this in your code
submitHandler: function() {
/*ajax request*/
}

jQuery how to handle the request answer in jQuery Validator?

email: {
required: true,
email: true,
remote: {
url: "/user/check_email",
type: "post",
data: {
email: function () {
return $("#email").val();
}
}
}
}
the server returns 1 or 0, but how in jQuery validator I can handle that result?
email: {
required: true,
email: true,
remote: {
url: "/user/check_email",
type: "post",
data: {
email: function() {
return $( "#email" ).val();
}
},
success: function(msg) {
alert(msg);
}
}
}
I've found it, just add a success function...

Trying to fire jquery validate on form submit using .submit

But it isn't firing when I hit submit. It submits but doesn't do anything. Any ideas? The alert doesn't even get called :(
The page I'm doing this on, is my Checkout page on:
http://rsatestamls.kaliocommerce.com
(Need a product in your cart to proceed to checkout)
My Javascript code is:
<script>
$(document).ready(function () {
$("#Method input:checkbox").change(function () {
if (this.checked) {
var checkname = $(this).attr("name");
$('input[type=checkbox][id=OnAccount]').prop('value', 'True')
$("input:checkbox[name='" + checkname + "']").not(this).removeAttr("checked");
} else {
$('input[type=checkbox][id=OnAccount]').val('No');
}
});
$("#CheckoutOptions input:checkbox").change(function () {
if (this.checked) {
var checkname = $(this).attr("name");
$("input:checkbox[name='" + checkname + "']").not(this).removeAttr("checked");
}
});
});
$("#CheckOut").submit(function (event) {
alert("Handler for .submit() called.");
jQuery.validator.setDefaults({
debug: false,
success: "valid"
});
$("#CheckOut").validate({
rules: {
FirstName: {
required: true
},
LastName: {
required: true
},
Email: {
required: true,
email: true
},
Phone: {
required: true,
digits: true
},
Address1: {
required: true
},
City: {
required: true
},
PostalCode: {
required: true,
digits: true
},
Country: {
required: true
},
State: {
required: true
},
pwd: {
required: true
},
pwd_confirm: {
required: true
},
FName_SHIP: {
required: true
},
LName_Ship: {
required: true
},
Phone_Ship: {
required: true,
digits: true
},
Address1_Ship: {
required: true
},
City_Ship: {
required: true
},
PostalCode_SHIP: {
required: true,
digits: true
},
COUNTRY_SHIP: {
required: true
},
State_SHIP: {
required: true
},
NameOnCard: {
required: {
depends: function (element) {
return $("#CCMethod").is(":checked");
}
}
},
CreditCardType: {
required: {
depends: function (element) {
return $("#CCMethod").is(":checked");
}
}
},
CardNumber: {
required: {
depends: function (element) {
return $("#CCMethod").is(":checked");
}
}
},
CardExpMonth: {
required: {
depends: function (element) {
return $("#CCMethod").is(":checked");
}
}
},
CardExpYear: {
required: {
depends: function (element) {
return $("#CCMethod").is(":checked");
}
}
},
CVC: {
required: {
depends: function (element) {
return $("#CCMethod").is(":checked");
}
}
},
customernumber: {
required: {
depends: function (element) {
return $("#OnAccount").is(":checked");
}
}
}
}
});
});
populateCartTotal();
</script>
Your submit handler isn't in your $(document).ready block, but should be. The handler is never getting attached.
In fact, you shouldn't use a submit handler at all, here. Just put your validate call in the ready block. See the demo here: http://jquery.bassistance.de/validate/demo/
<script>
$(document).ready(function () {
$("#Method input:checkbox").change(function () {
if (this.checked) {
var checkname = $(this).attr("name");
$('input[type=checkbox][id=OnAccount]').prop('value', 'True')
$("input:checkbox[name='" + checkname + "']").not(this).removeAttr("checked");
} else {
$('input[type=checkbox][id=OnAccount]').val('No');
}
});
$("#CheckoutOptions input:checkbox").change(function () {
if (this.checked) {
var checkname = $(this).attr("name");
$("input:checkbox[name='" + checkname + "']").not(this).removeAttr("checked");
}
});
// move this stuff to here
jQuery.validator.setDefaults({
debug: false,
success: "valid"
});
$("#CheckOut").validate({
rules: {
// all those rules here
}
});
});
populateCartTotal();
As an addendum to Ed's answer, I would also recommend setting up your validation scheme outside of the submit() handler.

Categories