Avatar of bigeven2002
bigeven2002
Flag for United States of America

asked on 

How do I add form validation to this code?

I have an AJAX based contact form that I am testing.  Using bootstrap and jQuery, the link is called in a modal window.  I have the form working and it will send email provided I fill in the fields correctly, but I haven't been able to figure out how to display an error message if validation fails.

The validation criteria is email and message files must not be blank and the email field must contain a valid formatted address.  Please see the following code for what I have.

HTML - I have a div ID set for form-ok and form-err.  I can get form-ok to appear but I don't know how to get form-err to appear if validation fails.
<a href="#contact" data-toggle="modal" class="navbar-text">Contact</a>

<div class="modal fade" id="contact" role="dialog">
    	<div class="modal-dialog">
        	<div class="modal-content">
            	<form id="contact-form" class="form-horizontal ajax" role="form" action="proc-contact.php" method="post">
                    
                    <div class="modal-header">
                        <h4>Contact Me <a class="close" data-dismiss="modal">x</a></h4>
                        
                    </div>
                    <div id="form-ok" class="alert alert-success">Thank You for your message.  I will reply as soon as possible.</div>
                    <div id="form-err" class="alert alert-danger">Sorry there was an error sending your message. Please check your entry.</div>
                    <div class="modal-body" id="modal-body-id">
                        
                        <div class="form-group">
                        	
                            <label for="contact-email" class="col-sm-2 control-label">E-mail:</label>
                            <div class="col-sm-10">
                            	<input type="email" name="email" class="form-control" id="contact-email" placeholder="you@example.com">
                            </div>
                        </div>
                        <div class="form-group">
                        	<label for="contact-message" class="col-sm-2 control-label">Message:</label>
                            <div class="col-sm-10">
                            	<textarea name="message" placeholder="Type your message..." id="contact-message" class="form-control" rows="6"></textarea>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <a class="btn btn-primary" data-dismiss="modal">Close</a>
                        <button class="btn btn-primary" id="new-message" type="reset">New Message</button>
                        <button class="btn btn-primary" value="1" name="submit" type="submit" id="submit">Send Message</button>
                    </div>
                </form>
                
            </div>
        </div>    
    </div>

Open in new window


JavaScript
$('form.ajax').on('submit', function() {
	var that = $(this),
		url = that.attr('action'),
		type = that.attr('method'),
		data = {};
		
	that.find('[name]').each(function(index, value) {
		var that = $(this),
			name = that.attr('name'),
			value = that.val();
			
		data[name] = value;
	});
	
	$.ajax({
		url: url,
		type: type,
		data: data,
		success: function(response) {
			$('#form-ok').show();
			$('#modal-body-id').hide();
			$('#submit').hide();
			$('#new-message').show();
			
				
			//
		}
	});
	
	return false;
});

$(document).ready(function(){
    $('#form-ok').hide();
	$('#form-err').hide();
	$('#new-message').hide();
	
	$("#new-message").click(function(){
		$("#contact-form")[0].reset();
		$('#modal-body-id').show();
		$('#new-message').hide();
		$('#submit').show();
		$('#form-ok').hide();
		$('#form-err').hide();
	});
	
});

Open in new window


PHP called by the form action, it counts the errors if any and returns the value from the function.  The if statements below are not functional.
<?php
	
	if($_POST["submit"]) {
	
		function chkEmlForm($frm) {
			
			$error = 0;
			
			$c_email = filter_var($frm['email'], FILTER_SANITIZE_EMAIL);
			$c_message = filter_var($frm['message'], FILTER_SANITIZE_STRING);
			
			$c_array = array($c_email,$c_message);
			
			foreach($c_array as $chk):
				if($chk==""):
					$error++;
				endif;
			endforeach;
			
			if(!filter_var($c_email, FILTER_VALIDATE_EMAIL)):
			  $error++;
			endif;
			
			if($error == 0):
				$toEmail = "me@domain.com";
				$subject = "Message from website";
				$headers = "from: ".$c_email."\nReply-To: ".$c_email;
				$content = "*** THIS MESSAGE IS FROM THE WEBSITE ***\n\n"
						  ."Email: ".$c_email."\n\n"
						  .stripslashes(trim($c_message));		
				mail($toEmail,$subject,$content,$headers);
				
			endif;
			
			return $error;
			
		}
		
		$err = chkEmlForm($_POST);
		
		
		if($err > 0):
			$result='<div id="form-alert" class="alert alert-danger">Sorry there was an error sending your message. Please check your entry.</div>';
		else:
			$result='<div id="form-alert" class="alert alert-success">Thank You for your message.  I will reply as soon as possible1.</div>';
		endif;
		
		
		
	}
	
	
?>

Open in new window

AJAXJavaScriptPHPHTMLScripting Languages

Avatar of undefined
Last Comment
bigeven2002

8/22/2022 - Mon