jQuery Stop submitting form by checking error variable - javascript

I have a simple form with some form fields. Some of them are required some are not. The required field are required by adding the class 'required'.
When I submit I check the #contact-form fields and on the basis of there I give the empty field error classes and submit the form yes or no.
Adding the error classes to the fields is not a problem, but checking the "error" variable is. Because I don't know where I can check the error variable.
This is my jQuery code:
$('#contact-form').submit(function (event) {
var errors = false;
$(this).find('.required').each(function () {
if ($(this).val().length < 1) {
$(this).addClass('error');
errors = true;
}
});
if (errors == true) {
event.preventDefault();
}
});
JsFiddle

The following code should do what you want, just give your contact form submit button the id of #contact-form-button.
$('#contact-form-button').click(function(e) { // using click function
// on contact form submit button
e.preventDefault(); // stop form from submitting right away
var error = false;
$(this).find('.required').each(function () {
if ($(this).val().length < 1) {
$(this).addClass('error');
error = true;
}
});
if (!error) { // if not any errors
$('#contact-form').submit(); // you submit form
}
});

$('#contact-form').submit(function (event) {
var errors = false;
$(this).find('.required').each(function () {
if ($(this).val().length < 1) {
$(this).addClass('error');
errors = true;
}
});
if (errors == true) {
event.preventDefault();
return false;
}
return true;
})
if validation cross successfully then it return true for submit the form

I found out that my code just works. The reason I thought it was not working, is because I was still using PHP handling my real website where I made 1 field required and in my jQuery not. This made the confusion.
So the following code works:
$('#contact-form').submit(function (event) {
var errors = false;
$(this).find('.required').each(function () {
if ($(this).val().length < 1) {
$(this).addClass('error');
errors = true;
}
});
if (errors == true) {
event.preventDefault();
}
});

Related

Jquery - allow form submit and override preventDefault()?

I have a function to test and make sure at least one form field is filled out:
function checkFields(form) {
var checks_radios = form.find(':checkbox, :radio'),
inputs = form.find(':input').not(checks_radios).not('[type="submit"],[type="button"],[type="reset"]');
var checked = checks_radios.filter(':checked');
var filled = inputs.filter(function(){
return $.trim($(this).val()).length > 0;
});
if(checked.length + filled.length === 0) {
return false;
}
return true;
}
And that is called when the form is submitted:
$(function(){
$('.checkThisForm').on('submit',function(e){
e.preventDefault();
var oneFilled = checkFields($(this));
if (!(oneFilled)) {
alert('You must fill in at least one field');
} else {
/* ??? */
}
});
});
What goes in my else { } to allow the form to submit if the user has supplied at least one element to search for in the form?
return for form action will indicate to proceed or stop the submission
$('.checkThisForm').on('submit',function(e){
var oneFilled = checkFields($(this));
if (!(oneFilled)) {
alert('You must fill in at least one field');
return false;
}
return true;
});
you are required to follow below info. First you need to triger click event and submit
$(function(){
$('.checkThisForm').on('click',function(e){
e.preventDefault();
var oneFilled = checkFields($(this));
if (!(oneFilled)) {
alert('You must fill in at least one field');
} else {
this.submit();
}
});

Maximum call stack size exceeded with jQuery promise()

I'm trying to apply a simple form validation in jQuery. If a form field is empty, add a class error. If any of the fields are empty, don't submit. I have the following:
$('#contact-form').submit(function(event) {
event.preventDefault();
var formValid = true;
$('input.required, textarea.required, select.required').each(function() {
if($(this).val() === '') {
formValid = false;
$(this).addClass('error');
} else {
$(this).removeClass('error');
}
}).promise().done(function() {
if(formValid) {
$('#contact-form').submit();
}
});
});
Howerver when the code hits the line to submit the form, I am seeing a JavaScript error:
Uncaught RangeError: Maximum call stack size exceeded
Here's how your code would run if the form is valid:
on submit, prevent default action
check fields
if they are valid, form.submit - which causes submit event, goto step 1
endless recursion
it's very simple because there's no asynchronous code in the handler
$('#contact-form').submit(function(event) {
var formValid = true;
$('input.required, textarea.required, select.required').each(function() {
if($(this).val() === '') {
formValid = false;
$(this).addClass('error');
} else {
$(this).removeClass('error');
}
});
if (!formValid) {
event.preventDefault();
}
});
How many fields do you have to validate, and why promise associated to each of them? try after checking all fields
if(formValid) {
$('#contact-form').submit();
}
else return false
$('#contact-form').submit(function(event) {
event.preventDefault();
var formValid = true;
$('input.required, textarea.required, select.required').each(function() {
if($(this).val() === '') {
formValid = false;
$(this).addClass('error');
} else {
$(this).removeClass('error');
}
}).promise().done(function() {
if(formValid) {
$("#contact-form").off('submit').submit();
}
});
return false;
});
First, .promise().done(...) can be purged. As has been said, nothing asynchronous is going on.
That aside, the actual issue is most likely the repeated re-invocation of the submit handler.
Try a POJS (as opposed to jQuery) form submission :
if(formValid) {
this.submit();
}

Get Value Of File Input for Validation

I've been using JQuery validation for all of my forms on my website but I've just started on an upload script for image files and it's not validating correctly. Here is the code that I have:
$(document).ready(function()
{
var avatarok = 0;
//Post Avatar
$('#avatar').blur(function()
{
var avatar=$("#avatar").val();
if(avatar.length < 1){
avatarok = 0;
}
else{
avatarok = 1;
}
});
// Submit button action
$('#avatarButton').click(function()
{
if(avatarok == 1)
{
$('.avatarValidation').addClass("sending");
$("#avatarForm").submit();
}
else
{
$('.avatarValidation').addClass("validationError");
}
return false;
});
//End
});
When I click on the button (avatarButton) it always shows the error class, even if a file has been selected. Any theories?
check the below solution and blur condition not executing so that u are getting same message
// Submit button action
$('#avatarButton').click(function()
{
var avatar=$("#avatar").val();
if(avatar == 1)
{
$('.avatarValidation').addClass("sending");
$("#avatarForm").submit();
}
else
{
$('.avatarValidation').addClass("validationError");
}
return false;
});
//End
and remove your blur function no use

"Merge" LiveValidation with Jquery on a form

This is part of my jquery function that validades a form i have on my website:
/*
validates errors on all the fieldsets
records if the Form has errors in $('#formElem').data()
*/
function validateSteps(){
var FormErrors = false;
for(var i = 1; i < fieldsetCount; ++i){
var error = validateStep(i);
if(error == -1)
FormErrors = true;
}
$('#formElem').data('errors',FormErrors);
}
/*
validates one fieldset
and returns -1 if errors found, or 1 if not
*/
function validateStep(step){
if(step == fieldsetCount) return;
var error = 1;
var hasError = false;
$('#formElem').children(':nth-child('+ parseInt(step) +')').find(':input:not(button)').each(function(){
var $this = $(this);
var valueLength = jQuery.trim($this.val()).length;
if(valueLength == ''){
hasError = true;
$this.css('background-color','#FFEDEF');
}
else
$this.css('background-color','#A8FC9C'); /* Campo preenchido */
});
var $link = $('#navigation_form li:nth-child(' + parseInt(step) + ') a');
$link.parent().find('.error,.checked').remove();
var valclass = 'checked';
if(hasError){
error = -1;
valclass = 'error';
}
$('<span class="'+valclass+'"></span>').insertAfter($link);
return error;
}
/*
if there are errors don't allow the user to submit
*/
$('#enviar_candidatura').bind('click',function(){
var preenchimentoForm=true;
if($('#formElem').data('errors')){
preenchimentoForm=false;
dadosFormularios(preenchimentoForm);
//return false;
}
else{
dadosFormularios(preenchimentoForm);
}
});
});
However, i'm using too LiveValidation (http://livevalidation.com/) to validade fields client-side. Obiously, if the part validated by jquery is Ok, doesn't matter if there's errors on the LiveValidation part because the form is submitted.
So, what i want is to add an if clause or something like that inside this jquery code to verify if there are LV_invalid_fields. If 'yes' then block form from submitting like it's done with the jquery validation part, but i don't know how to do it neither where is the right place in the code above to put this verification. I would appreciate some help. Thanks!
//... live validation codes here
$("#myform").submit( function (event) ) {
event.preventDefault();
if ($(".LV_invalid").length > 0) {
//do not submit
}
else {
//do form submission here
}
}
First, you have to change the binding on the click to a binding on the submit action on the form.
And your function must return false on the submit action to stop the submitting action.
So, change your code like this :
$('#formElem').submit( function (event) ) {
var preenchimentoForm = true;
if ($('#formElem').data('errors')){
preenchimentoForm = false;
}
return preenchimentoForm;
}
You can read some explications about unobtrusive javascript here.
There is an option in the LiveValidation library which is not explained in the documentation http://livevalidation.com/documentation
To prevent LiveValidation's submission while still keeping its validation events, you may use the "afterValidation" option.
Example:
var prevent = function (e) {
e.preventDefault();
};
var yourValidation = new LiveValidation(
"inputID", {
//Your other options
afterValidation: prevent
}
);
yourValidation.add( Validate.Presence, { your options } );

Chrome fails on jquery form validation

Can someone explain to me why the form validation fails in chrome?
Pressing the submit should colour empty fields red.
I have no idea why chrome fails - would be glad to find a solution...
$('form .meet').focus(function() {
$('form .required').each(function() {
if($(this).val() == '') {
$(this).addClass('warning');
}
})
});
$('form .meet').click(function() {
output = true;
if($('form .warning').length > 0) {
$(this).addClass('disabled').attr('disabled','disabled');
output = false;
}
return output;
});
$('form .required').keyup(function() {
if($(this).val()) {
$(this).removeClass('warning');
if($('form .warning').length == 0) {
$('form .meet').removeClass('disabled').removeAttr('disabled');
}
}
});
.required are the input field that may not be empty
.meet are the submit fields related to .required
In Chrome, the click event fires before focus. Your code expects the focus event to occur first (to assign warning class to empty inputs). You should perform the input field value assessment on click.
$('form .meet').click(function() {
output = true;
$('form .required').each(function() {
if($(this).val() == '') {
$(this).addClass('warning');
}
});
if($('form .warning').length > 0) {
$(this).addClass('disabled').attr('disabled','disabled');
output = false;
}
return output;
});

Categories

Resources