As already explained:
- do basic validation client-side with JS. IMHO 99% of people have it enabled
- do full validation server side.
For client side validation use pure JS or JQuery (or similar tool) to display a error message next to the erroneous field.
For server side validation I use the Session variable to return data to the form but you could also use GET or POST. I will use POST in this example.
I prefer the paradigm that the form posts to a separate PHP file that is for processing only with not display logic. This processing file does the validation. In case it finds errors it will put them into an array with field name = > validation error message. This array is then added to
and the submitted form values are also added to $_POST again.
On the form which must also be a PHP file you have for each input field:
PHP:
<form class="cssform" action="processData.php" method="post">
<div>
<label for="myField">My Field</label>
<input type="text" id="myField" name="myField"
value="<?php echo !empty($_POST['myField']) ? $_POST['myField'] : ''; ?>"/>
<?php
if (isset($_POST["validation"]['myField'])) {
echo "<span class='error'>{$_POST["validation"]['myField']}</span>";
}
?>
</div>
</form>
To make this display correctly you need some CSS. See end of this post.
So basically when the form is loaded it will automatically display the initially submitted values again so user does not have to retype everything and it will show an error message next to the input causing the issue.
Example:
Code:
.cssform {
padding-top: 2em;
padding-bottom: 2em;
}
.cssform div {
max-width: 680px;
clear: left;
margin: 0;
padding: 5px 0 8px 0;
padding-left: 155px; /*width of left column containing the label elements*/
}
.cssform label {
color: #990033;
font-weight: bold;
float: left;
margin-left: -155px; /*width of left column*/
width: 150px; /*width of labels. Should be smaller than left column (155px) to create some right margin*/
}
.cssform input[type="text"]{ /*width of text boxes. IE6 does not understand this attribute*/
width: 180px;
padding-bottom: 5px
}
.error {
/* obviously you don't have the image but search one or leave it away */
background: #fff3f3 url(../images/skin/exclamation.png) 4px 50% no-repeat;
border: 1px solid red;
color: #cc0000;
padding: 5px 5px 5px 30px;
margin-top: 0px;
margin-left: 15px;
}