Improve company productivity with a Business Account.Sign Up

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 150
  • Last Modified:

ajax form sumbit

Hello Experts,

For some reason even when all the required fields are left empty the form is being submitted. I re-checked the script below couple of times and yet i am not sure why the form submission executes when the required fields are left empty or are not valid.
Can anyone please help me?


$(document).ready(function() {
	
	var form = $('#enquiry-form');
			
	var requiredInput = $("#enquiry-form input[inputRequired], #enquiry-form textarea[inputRequired]");
	var validEmail = new RegExp(/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/);	
	
	
	// fields validation function
	var validateRequired = function(evt) {		
	 
		$(requiredInput).each(function() {
		
			if (($.trim($(this).val() )=== "") || ($.trim($(this).val()).length <= 2)) {
			
				$(this).addClass("error");
			
				if ($(this).is('#first_name')) {					  
					$(this).parent().find(".placeholder").text("Please enter your name");					
				} else if ($(this).is('#last_name')) {
					$(this).parent().find(".placeholder").text("Please enter your last name");				
				} else if ($(this).is('#email')) {				 
					$(this).parent().find(".placeholder").text("Please enter your email address");	
				}
				
				evt.preventDefault();		
				
			} else {
				$(this).removeClass("error");
				$(this).parent().find(".placeholder").text("");
			}
		});
	};
	// end fields validation function
	
	// email validation function
	
	var validateEmail = function(evt) {
		
		if($(this).val().match(validEmail)) {
						
			$(this).removeClass("error");
		} else {
			$(this).addClass("error");
			$(this).parent().find(".placeholder").text("Please enter a valid email address");
			evt.preventDefault();
		}
	};
	// end email validation function	
		
	$(requiredInput).blur(validateRequired);
	$("#email").blur(validateEmail);
	
			
	$(form).on("submit", function(evt) {
		evt.preventDefault();	
		
		validateRequired.call($(requiredInput),evt);
		
		if (validateRequired.call($(requiredInput),evt) && validateEmail.call($('email'),evt)) {		
			formError();		
		} else {
			submitForm();		
		}		
	});	
	
	function submitForm() {
		
		var formData = $(form).serialize();
		
		var first_name = $("#first_name").val();
               var last_name = $("#last_name").val();
               var email = $("#email").val();
		var oid = '0000';
		var lead_source = 'Exclusive....';
		
		$.ajax({
			type: "POST",
			url: "https://www.salesforce.com/......",
			dataType: "json",
			data: formData,
			
			complete: function() {
				 $(form).css("opacity", 0.5);
				 $(".enquiry-confirmation").show();
        	}
			
		});
			
		
	} // end of submitForm function
	
	function formError() {
		// printing some error text
	}
	
});
	
	

Open in new window

0
Refael
Asked:
Refael
2 Solutions
 
KarenAnalyst programmerCommented:
First thing I notice is that you are not returning anything from your functions to tell the calling routine whether they were successful or not.
So your code will always hit the 'else' part of the condition.
Something like this:

	var validateRequired = function(evt) {		
		var allValid = true;                              // *******************
		$(requiredInput).each(function() {
			if (($.trim($(this).val() )=== "") || ($.trim($(this).val()).length <= 2)) {
			        allValid = false;                 // *******************
				$(this).addClass("error");
			
				if ($(this).is('#first_name')) {					  
					$(this).parent().find(".placeholder").text("Please enter your name");					
				} else if ($(this).is('#last_name')) {
					$(this).parent().find(".placeholder").text("Please enter your last name");				
				} else if ($(this).is('#email')) {				 
					$(this).parent().find(".placeholder").text("Please enter your email address");	
				}				
				evt.preventDefault();						
			} else {
				$(this).removeClass("error");
				$(this).parent().find(".placeholder").text("");
			}
		});
		return AllValid;          // *******************
	};
	var validateEmail = function(evt) {
		if($(this).val().match(validEmail)) {						
			$(this).removeClass("error");
			return true;          // *******************
		} else {
			$(this).addClass("error");
			$(this).parent().find(".placeholder").text("Please enter a valid email address");
			evt.preventDefault();
			return false;          // *******************
		}
	};
			
	$(form).on("submit", function(evt) {
...
// I think you want your selector here to be #email instead of email		
		if (validateRequired.call($(requiredInput),evt) && validateEmail.call($('#email'),evt)) {		
			// both returned 'true' so can submit the form
			submitForm();		
		} else {
			// there was at least one problem, so do not submit the form
			formError();		
		}		
	});	

Open in new window

0
 
Andrew DerseIT ManagerCommented:
You are also calling the values way to late to be validated...those need to be the very first step.

Also it would be great to break out the functions into smaller chunks like this...it's not 100% correct, but it's going to get you started in the right direction:
function prepForm() {
    var form = $('#enquiry-form');
    
    var formData = $(form).serialize();
    var first_name = $("#first_name").val();
    var last_name = $("#last_name").val();
    var email = $("#email").val();
    var oid = '0000';
    var lead_source = 'Exclusive....';
    
    var requiredInput = $("#enquiry-form input[inputRequired], #enquiry-form textarea[inputRequired]");
    var validEmail = new RegExp(/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/);


    // fields validation function
    var validateRequired = function(evt) {

        $(requiredInput).each(function() {

            if (($.trim($(this).val() )=== "") || ($.trim($(this).val()).length <= 2)) {

                $(this).addClass("error");

                if ($(this).is('#first_name')) {
                    $(this).parent().find(".placeholder").text("Please enter your name");
                } else if ($(this).is('#last_name')) {
                    $(this).parent().find(".placeholder").text("Please enter your last name");
                } else if ($(this).is('#email')) {
                    $(this).parent().find(".placeholder").text("Please enter your email address");
                }

                evt.preventDefault();

            } else {
                $(this).removeClass("error");
                $(this).parent().find(".placeholder").text("");
            }
        });
    };
    // end fields validation function

    // email validation function

    var validateEmail = function(evt) {

        if($(this).val().match(validEmail)) {

            $(this).removeClass("error");
        } else {
            $(this).addClass("error");
            $(this).parent().find(".placeholder").text("Please enter a valid email address");
            evt.preventDefault();
        }
    };
    // end email validation function	

    $(requiredInput).blur(validateRequired);
    $("#email").blur(validateEmail);


    $(form).on("submit", function(evt) {
        evt.preventDefault();

        validateRequired.call($(requiredInput),evt);

        if (validateRequired.call($(requiredInput),evt) && validateEmail.call($('email'),evt)) {
            formError();
        } else {
            submitForm( formData );
        }
    });
}
function submitForm( formData ) {
    
    $.ajax({
        type: "POST",
        url: "https://www.salesforce.com/......",
        dataType: "json",
        data: formData,

        complete: function() {
            $(form).css("opacity", 0.5);
            $(".enquiry-confirmation").show();
        }

    });


} // end of submitForm function

function formError() {
    // printing some error text
}

$(document).ready(function() {
    prepForm();
});
	
	

Open in new window

0
 
RefaelAuthor Commented:
Karen and Andrew thank you so much!
Learning from your code and your comments helps me to be a better coder :-)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Get expert help—faster!

Need expert help—fast? Use the Help Bell for personalized assistance getting answers to your important questions.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now