We help IT Professionals succeed at work.

Form validation - error/success message placement

digitalPencil
on
2,920 Views
Last Modified: 2012-05-05
Hi,

I've got a php mail form which uses a combination of javascript and php to validate form data.
The javascript traps errors using livevalidation and displays an asterix next to any empty fields and php traps any other errors like invalid email format, spamwords etc.

The problem is that, the asterix that should be displayed next to the message textarea, is displayed below it, and i would like to move the php success/error messages so they are center aligned instead of at the top of the page which is where they currently display.

I'm pretty new to php, so how would I center align the success/error messages? and, why does the textarea asterix display beneath it instead of displaying at the side?

The form's at davegrant.info/contact.php
and code is attached to this post.

Thanks

<?php
if (isset($_POST['submit'])) 
{
        $error = '';
        $msg = '';
        $exploits = "/(content-type|bcc:|cc:|document.cookie|onclick|onload|javascript|alert)/i";
        $profanity = "/(beastial|bestial|blowjob|clit|cock|cum|cunilingus|cunillingus|cunnilingus|cunt|ejaculate|fag|felatio|fellatio|fuck|fuk|fuks|gangbang|gangbanged|gangbangs|hotsex|jism|jiz|kock|kondum|kum|kunilingus|orgasim|orgasims|orgasm|orgasms|phonesex|phuk|phuq|porn|pussies|pussy|spunk|xxx)/i";
        $spamwords = "/(viagra|phentermine|tramadol|adipex|advai|alprazolam|ambien|ambian|amoxicillin|antivert|blackjack|backgammon|texas|holdem|poker|carisoprodol|ciara|ciprofloxacin|debt|dating|porn)/i";
        $bots = "/(Indy|Blaiz|Java|libwww-perl|Python|OutfoxBot|User-Agent|PycURL|AlphaServer)/i";
        
        if (preg_match($bots, $_SERVER['HTTP_USER_AGENT'])) 
        {
        $error .= 'Known spam bots are not allowed.';
        }
        else
        {
                foreach ($_POST as $key => $value) 
                {
                $value = trim($value);
                
                        if (empty($value)) 
                        {
                        $msg .= 'Validation Error: Empty fields<br />';
                        } 
                        elseif (preg_match($exploits, $value)) 
                        {
                        $msg .= 'Validation Error: Malicious scripting attributes found!<br />';
                        } 
                        elseif (preg_match($profanity, $value) || preg_match($spamwords, $value)) 
                        {
                        $msg .= 'Validation Error: Profanity and/or spamwords found!<br />';
                        }
                        
                        $_POST[$key] = stripslashes(strip_tags($value));
                        }
                
                        if (!ereg("^[_a-z0-9-]+(.[_a-z0-9-]+)*@[a-z0-9-]+(.[a-z0-9-]+)*(.[a-z]{2,6})$",strtolower($_POST['email']))) 
                        {
                        $msg .= 'Validation Error: Invalid email format<br />';
                        }
                        
                        if($msg == '')
                        {
        
                        $recipient = "davegrant85@gmail.com";
                        $subject = "davegrant.info Contact Form";
                        
                        $message = "Contact form mail from davegrant.info: \n";
                        $message .= "Name: {$_POST['name']} \n";
                        $message .= "E-mail: {$_POST['email']} \n";
                        $message .= "Website: {$_POST['website']} \n";
                        $message .= "Feedback: {$_POST['comments']} \n";
                        
                        $headers = "From: davegrant.info <$recipient> \n";
                        $headers .= "Reply-To: <{$_POST['email']}>";
                        
                                if (mail($recipient,$subject,$message,$headers)) 
                                {
                                $msg .= 'Thank you! Your mail was successfully sent to the webmaster. Thank you for your time.';
                                } 
                                else 
                                {
                                $error .= 'Sorry, there was an error and your mail was not sent. Please find an alternative method of contacting the webmaster.';
                                }
                        }
                }
}
?>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>davegrant - web &amp; graphic designer</title>
<link rel="stylesheet" href="style_con.css" type="text/css" media="screen" />
<script type="text/javascript" src="livevalidation.js"></script>
<style type="text/css">
<!--
.style4 {
	font-size: 13px
}
.button {
	color: #fff;
	background: transparent;
	border: 1px solid #501936;
	padding:4px 15px 4px 15px;
}
input {
	background:none;
	background-color:transparent;
	border:1px solid #501936;
	padding:4px;
	margin-top:3px;
	font-family:"Lucida Grande", "Lucida Sans Unicode", Arial, Sans-serif;
	font-size:11px;
	color:#fff;
}
textarea {
	background:none;
	background-color:transparent;
	border:1px solid #501936;
	padding:4px;
	margin-top:3px;
	font-family:"Lucida Grande", "Lucida Sans Unicode", Arial, Sans-serif;
	font-size:11px;
	color:#fff;
	width:350px;
}
/* Validation Styles - Tweak as needed */
.LV_validation_message{
    font-weight:normal;
    margin:0 0 0 5px;
}
 
.LV_valid {
    color:#501936;
}
	
.LV_invalid {
    color:#7d3370;
}
    
.LV_valid_field,
input.LV_valid_field:hover, 
input.LV_valid_field:active,
textarea.LV_valid_field:hover, 
textarea.LV_valid_field:active {
    border: 1px solid #501936;
}
    
.LV_invalid_field, 
input.LV_invalid_field:hover, 
input.LV_invalid_field:active,
textarea.LV_invalid_field:hover, 
textarea.LV_invalid_field:active {
    border: 1px solid #7d3370;
}
-->
</style>
<script src="Scripts/AC_RunActiveContent.js" type="text/javascript"></script>
</head>
<body>
<div id="outside_container">
	<div id="container"> <a href="http://www.davegrant.info/"><img src="images/logo.jpg" width="286" height="50" id="logo" /></a>
		<ul id="menu">
			<li><a href="index.html">HOME</a></li>
			<li><a href="folio.html">PORTFOLIO</a></li>
			<li><a href="contact.php">CONTACT</a></li>
		</ul>
		<div id="content">
			<div class="column1">
				<h2>contact</h2>
				<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Vivamus non ligula nec sem posuere consectetuer. Proin sagittis diam sed sapien. Aliquam sem turpis, semper at, rhoncus in, aliquam at, lorem. Maecenas purus metus.</p>
			</div>
			<div class="column2">
				<p> name<br />
					address<br />
					address<br />
					address<br />
					address<br />
				</p>
			</div>
			<div class="column3">
				<p> email[at]email.com
					[00]00000001 </p>
			</div>
			<div class="column4">
				<?php 
				if((isset($msg)) && ($msg != ''))
				{
				echo '<p>' . $msg . '</p>' . "\n";
				}
				else
				{
					if((isset($error)) && ($error != '')) 
					{
					echo '<p>' . $error . '</p>' . "\n";
					}
					?>
					<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
                                                Name:<br>
                                                <input type="text" id="name" name="name"<?php if(isset($_POST['name'])){echo ' value="' . $_POST['name'] . '"';} ?> class="required">
                                                <br>
                                                <script type="text/javascript">
                                                var name = new LiveValidation('name');
                                                name.add( Validate.Presence );
                                                </script>
                                                <br />
                                                
												Email:<br>
                                                <input type="text" id="email" name="email"<?php if(isset($_POST['name'])){echo ' value="' . $_POST['email'] . '"';} ?> class="required">
                                                <br>
                                                <script type="text/javascript">
                                                var name = new LiveValidation('email');
                                                name.add( Validate.Presence );
                                                </script>
                                                <br />
												
                                                Website:<br>
                                                <input type="text" id="website" name="website"<?php if(isset($_POST['website'])){echo ' value="' . $_POST['website'] . '"';} ?> class="required">
                                                <br>
                                                <script type="text/javascript">
                                                var website = new LiveValidation('website');
                                                website.add( Validate.Presence );
                                                </script>
                                                <br />
                                                Message:<br>
                                                <textarea id="comments" name="comments" rows="10" cols="30"><?php if(isset($_POST['comments'])){echo $_POST['comments'];} ?></textarea>
                                                <br>
                                                <script type="text/javascript">
                                                var comments = new LiveValidation('comments');
                                                comments.add( Validate.Presence );
                                                </script>
                                                <br />
                                                <input type="submit" name="submit" value="Send" class="button">
                                        </form>
				<?php } ?>
			</div>
			<div style="clear:both"></div>
		</div>
	</div>
</div>
<div id="footer"> <img src="images/footer_logo.png" width="124" height="24" /> <span id="footer_text"> Portfolio for web and graphic designer, Dave Grant.<br />
	To find out more, <a href="folio.html">See my Work</a>, 
	or <a href="contact.html">Contact</a> me</span> </div>
</body>
</html>

Open in new window

Comment
Watch Question

Hi again digitalPencil -

I feel bad you had to open a separate q for this. :)

To style the message error for the form success or php validation errors you just need to add a class name to the paragraph for each message output and then style those classnames however you want in your css.  The following is an example of class names you can use:
// Line 171 - Submission confirmation message
 
//Current
echo '<p>' . $msg . '</p>' . "\n";
 
//Replace with (and style the classname in your css)
echo '<p class="formMsg">' . $msg . '</p>' . "\n";
 
 
// Line 177 - PHP validation error
 
// Current
echo '<p>' . $error . '</p>' . "\n"
 
// Replace with (and style your class in your stylesheet)
echo '<p class="formError">' . $error . '</p>' . "\n"

Open in new window

Also forgot to mention that for the asterisk problem on the textarea - just try reducing the width of the textarea in your css.  It's currently set to 350px.  Try dropping it down 50px so the asterisk can fit on the right.

Author

Commented:
Hi again and no worries, i didn't feel i could keep pestering you after you sorted all this form out for me :)

Thanks, that's worked great.. any ideas on the asterix part though?
I'm not sure why it displays beneath the textarea when it sits on the side of the input fields...
Did you try my fix above about reducing the textarea width?  It looks like there isn't enough room for it to fit in the same line, so it drops down.

Author

Commented:
Sorry, i hadn't seen that. Yes the problem was the css, i've increased the size of the holding div to 380px to allow enough space for the asterix to display. Only trouble is that it aligns to the base of the textarea, is there any way to move it to the top?

see: http://www.davegrant.info/contact.php

Thanks again.
I know there's a way to create a separate style for some of the validation messages...I just can't remember how. :)  I'm heading out right now, but if you look through the live validation documents on their website for the section regarding styles...you should see where they explain how to do it.

Essentially what you need to do is create a separate LV_ style for the textarea so you can set a line-height or margin-bottom to the container holding the error message.  I think they use a span as the container...which means you'd have to set it to 'display:block; float:left;' which allows you to modify the top/bottom spacing while still keeping it to the right of the textarea.

Will check in again when I get back from my errands...
textarea is a weird bird -- you cannot put anything next to it, the next logical position after the text area is BELOW it.  You would have to do this to get it to work

TABLE
TR
TD <input type=textarea>
TD  
TR
TABLE

now you write the asterisk state by -
document.getElementById('asterisk'").innerHTML = ' * ';

Do likewise to align the main messages.  Put the input in the first TD, then a SPAN for the messages in the next TD.

You can do this with purely CSS, but it is a bloody lot of work, when it goes easy into a table.
again, this EE input box is deleting the HTML I write -- very frustrating.
See the correct table in the code below --

<TABLE>
<TR>
<TD> <input type ="textarea"> </input>
<TD valign="middle"> <SPAN id="asterisk"> </SPAN> </TD>
</TR>
</TABLE>
 
then write to the span id=asterisk and it will be right of the textarea

Open in new window

This one is on us!
(Get your first solution completely free - no credit card required)
UNLOCK SOLUTION
"textarea is a weird bird -- you cannot put anything next to it, the next logical position after the text area is BELOW it.  You would have to do this to get it to work"

- He'd already gotten the asterisk next to the textarea by floating it to the left.  What he was trying to do now was just make it so the asterisk appeared in the vertical-middle of the textarea instead of at the lower-right side.  You can see the issue by visiting his contact page posted above and trying to submit the empty form (which triggers the validation)

Author

Commented:
Thanks logicalinsanity, works a treat!

Gain unlimited access to on-demand training courses with an Experts Exchange subscription.

Get Access
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Empower Your Career
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE

Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Unlock the solution to this question.
Join our community and discover your potential

Experts Exchange is the only place where you can interact directly with leading experts in the technology field. Become a member today and access the collective knowledge of thousands of technology experts.

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.