Ajax form and jQuery validation

Hello Experts,

Below are two blocks of code:

The first block of code is basically a jQuery form validation.
The second block of code is a code that should process only once the validation has passed successfully.

I am not an expert... what i am trying to understand is where to insert the the second block of code.

I am thinking that this should be in the submit click function yet it needs to check first if the validations has passed meaning there is no errors. Thank you for you help!

var form = $('#vContact');
var formMessages = $('#form-messages');	
	
	var requiredInput = $("#vContact input[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,}))$/);
	
	var validateRequired = function(evt) {	 
	 
	    $(requiredInput).each(function() {
					  
		  if (($.trim($(this).val() )=== "") || ($.trim($(this).val()).length <= 2)) {
							  
			  $(this).addClass("error");			  			  
			   evt.preventDefault();
		  } else {
			  $(this).removeClass("error");			  
		  }
		});
	 };
	 
	 var validateEmail = function(evt) {
		
		if($(this).val().match(validEmail)) {
			$(this).removeClass("error");
		} else {
			$(this).addClass("error");			
			evt.preventDefault();
		}
	 };
	 
	 $(requiredInput).blur(validateRequired);
	 $("#email").blur(validateEmail);
	
	
	 $("#submit").click(function(evt) {
		validateRequired.call($(requiredInput),evt);
                validateEmail.call($('#email'),evt);
		
	 });
});

Open in new window




var formData = $(form).serialize();
		
		$.ajax({
			type: 'POST',
			url: $(form).attr('action'),
			data: formData
		})		
		.done(function(response) {
						
			$(formMessages).text(response);
		
			$('#name').val('');
			$('#email').val('');
			$('#phone').val('');
		})

Open in new window

RefaelAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Julian HansenCommented:
 $("#submit").click(function(evt) {
		validateRequired.call($(requiredInput),evt);
                validateEmail.call($('#email'),evt);
		/* HERE *
               return false;
	 });

Open in new window

But you will need to have your validate functions return a value - you don't want to submit unless they pass - so something like

 
$("#submit").click(function(evt) {
		if (validateRequired.call($(requiredInput),evt) && 
                validateEmail.call($('#email'),evt)) {
                   // AJAX HERE
                   // RETURN FALSE - DISABLE DEFAULT SUBMIT PROCESS
		}
	 });

Open in new window


You will of course need to change your validateEmail and validateRequired to return either true or false depending on whether validation succeeded or not.
0
RefaelAuthor Commented:
Hello Julian :-)

Thank you. Can I do it like this?

 $("#submit").click(function(evt) {
		 
		if (validateRequired.call($(requiredInput),evt) && validateEmail.call($('#email'),evt)) {
		
			var formData = $(form).serialize();
			
			$.ajax({
				type: 'POST',
				url: $(form).attr('action'),
				data: formData
			})				
			.done(function(response) {
											
				$(formMessages).text(response);
			
				$('#name').val('');
				$('#email').val('');
				$('#phone').val('');
			})
		} else {
			evt.preventDefault();
		}			
			
	 });

Open in new window

0
Julian HansenCommented:
Yes - but I wouldn't - it is not good design.

Keep your validation routines doing what they do - checking input. They return values which are then used to decide whether you should fire the AJAX or not.
0
Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

RefaelAuthor Commented:
Julian so i should use the "return false" as you did? Is that what you are saying?

$("#submit").click(function(evt) {

               if (validateRequired.call($(requiredInput),evt) && validateEmail.call($('#email'),evt)) {
		
			var formData = $(form).serialize();
			
			$.ajax({
				type: 'POST',
				url: $(form).attr('action'),
				data: formData
			})				
			.done(function(response) {
											
				$(formMessages).text(response);
			
				$('#name').val('');
				$('#email').val('');
				$('#phone').val('');
			})
                         return false;		
		}			
			
	 });

Open in new window

0
Julian HansenCommented:
No like this
var form = $('#vContact');
var formMessages = $('#form-messages');  
  
  var requiredInput = $("#vContact input[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,}))$/);
  
  var validateRequired = function(evt) {   
    // DEFAULT RETURN RESULT  
    var result = true;
    
      $(requiredInput).each(function() {
      if (($.trim($(this).val() )=== "") || ($.trim($(this).val()).length <= 2)) {
        $(this).addClass("error");                
        evt.preventDefault();
    // SET RESULT TO FALSE - THERE WERE ERRORS
        result = false;
      }
      else {
        $(this).removeClass("error");        
      }
    });
  
    // RETURN THE ERRORS
    return result;
   };
   
   var validateEmail = function(evt) {
    // DEFAULT RETURN RESULT  
    var result = true;
    if($(this).val().match(validEmail)) {
      $(this).removeClass("error");
    } else {
      $(this).addClass("error");      
      evt.preventDefault();
    
      // SET RESULT TO FALSE - THERE WERE ERRORS
      result = false;
    }
  
    // RETURN THE ERRORS
    return result;
   };
   
   $(requiredInput).blur(validateRequired);
   $("#email").blur(validateEmail);
  
  
   $("#submit").click(function(evt) {
    if (validateRequired.call($(requiredInput),evt) && 
            validateEmail.call($('#email'),evt)) {
      // AJAX HERE
      var formData = $(form).serialize();
      
      $.ajax({
        type: 'POST',
        url: $(form).attr('action'),
        data: formData,
        success: function(response) {
          $(formMessages).text(response);
      
          $('#name').val('');
          $('#email').val('');
          $('#phone').val('');
        }
      })        
    }
   });
});

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
RefaelAuthor Commented:
Sorry Julian I was away. Your solution is great and already is integrated and working as expected. Thank you!
0
Julian HansenCommented:
You are welcome.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
AJAX

From novice to tech pro — start learning today.

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.