Adding Server-side Capabilities to Form Validation with the DOM - Assembling the client and server-side modules of the application
(Page 5 of 5 )
As I expressed in the prior section, now I’ll set up an example that demonstrates how to use the DOM-driven form validation script created in the preceding articles, in conjunction with the form checking class that you learned a few lines above.
The code sample includes the definition of two files, called “dom_validator.php” and form_validator.php” respectively, which naturally perform the validation of form data in the client and the server:
// definition for “dom_validator.php” file
<!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">
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=iso-8859-1" />
<title>DOM-based form validator</title>
<script language="javascript">
// validate form
function validateForm(formObj){
valid=true;
var fname=formObj.elements[0];
if(!fname){return};
if(!fname.value){showError(fname,'Enter your First Name')};
var lname=formObj.elements[1];
if(!lname){return};
if(!lname.value){showError(lname,'Enter your Last Name')};
var email=formObj.elements[2];
if(!email){return};
if(!email.value){showError(email,'Enter your email address')};
var age=formObj.elements[3];
if(!age){return};
if(!age.value){showError(age,'Enter your age (1-99)')};
var postadd=formObj.elements[4];
if(!postadd){return};
if(!postadd.value){showError(postadd,'Enter your postal address')};
return valid;
}
// display error messages
function showError(obj,message){
if(!obj.errorNode){
obj.onchange=hideError;
var span=document.createElement('span');
span.className='error';
span.appendChild(document.createTextNode(message));
obj.parentNode.appendChild(span);
obj.errorNode=span;
}
valid=false;
return
}
// hide error messages
function hideError(){
this.parentNode.removeChild(this.errorNode);
this.errorNode=null;
this.onchange=null;
}
// execute 'ValidateForm()'
function when page is loaded
window.onload=function(){
// check if browser is W3CDOM compatible
if(document.getElementById&&document.
getElementsByTagName&&document.createElement){
var theform=document.getElementsByTagName('form')[0];
if(theform){theform.onsubmit=function(){return
validateForm(this)}};
}
}
</script>
<style
type="text/css">
body{
margin: 0;
padding: 0;
background: #fff;
}
h1{
font: bold 18px Arial, Helvetica, sans-serif;
color: #000;
text-align: center;
}
span{
font: bold 12px Arial, Helvetica, sans-serif;
color: #f00;
margin-left: 10px;
}
ul{
font: bold 12px Arial, Helvetica, sans-serif;
color: #f00;
text-align: center;
}
#formcontainer{
width: 600px;
height: 450px;
background: #eee;
margin-left: auto;
margin-right: auto;
border: 1px solid #ccc;
}
#labelcontainer{
float: left;
width: 200px;
text-align: right;
padding-right: 10px;
}
#labelcontainer p{
font: normal 12px Arial, Helvetica, sans-serif;
color: #000;
margin: 10px 0 0 0;
}
#boxcontainer{
float: left;
width: 300px;
}
#boxcontainer p{
font: normal 12px Arial, Helvetica, sans-serif;
color: #000;
margin: 4px 0 0 0;
}
</style>
</head>
<body>
<?php require_once 'form_validator.php';?>
<div id="formcontainer">
<form action="<?php echo $_SERVER['PHP_SELF']?>"method="post">
<div id="labelcontainer">
<p>First Name</p>
<p>Last Name</p>
<p>Email</p>
<p>Age</p>
<p>PostalAddress</p>
<p>Comments</p>
</div>
<div id="boxcontainer">
<p><input type="text" name="fname" /></p>
<p><input type="text" name="lname" /></p>
<p><input type="text" name="email" /></p>
<p><input type="text" name="age" /></p>
<p><input type="text" name="paddress" /></p>
<p><textarea rows="10" cols="20"></textarea></p>
<p><input type="submit" name="send" value="Send Data"
/></p>
</div>
</form>
</div>
</body>
</html>
// definition for “form_validator.php” file
<?php
class FormValidator{
private $errors=array();
private $method;
const MIN=4;
const MAX=32;
public function __construct(){
$this->method=$_POST;
}
// validate empty values
public function validateEmpty($field,$errorMessage){
if(!$this->method[$field]||trim($this->
method[$field])==''||strlen($this->method[$field])
<self::MIN||strlen($this->method[$field])>self::MAX){
$this->errors[]=$errorMessage;
}
}
// validate integer values
public function validateInt($field,$errorMessage){
if(!$this->method[$field]||!is_numeric($this->
method[$field])||intval($this->method[$field])!=$this->method[$field]){
$this->errors[]=$errorMessage;
}
}
// validate numeric values
public function validateNumber($field,$errorMessage){
if(!$this->method[$field]||!is_numeric($this->method[$field])){
$this->errors[]=$errorMessage;
}
}
// validate range of values
public function validateRange($field,$errorMessage){
if(!$this->method[$field]||$this->
method[$field]<self::MIN||$this->method[$field]>self::MAX){
$this->errors[]=$errorMessage;
}
}
// validate alphanumeric values
public function validateAlphanum($field,$errorMessage){
if(!$this->method[$field]||!preg_match
("/^[a-zA-Z0-9]+$/",$this->method[$field])){
$this->errors[]=$errorMessage;
}
}
// validate email address
public function validateEmail($field,$errorMessage){
if(!$this->method[$field]||!preg_match
("/.+@.+..+./",$this->method[$field])||!checkdnsrr
(array_pop(explode("@",$this->method[$field])),"MX")){
$this->errors[]=$errorMessage;
}
}
// validate email address (Windows systems)
public function validateEmailWin($field,$errorMessage){
if(!$this->method[$field]||!preg_match
("/^.+@.+..+$/",$this->method[$field])||!$this->windnsrr
(array_pop(explode("@",$this->method[$field])),"MX")){
$this->errors[]=$errorMessage;
}
}
private function windnsrr($hostName,$recType=''){
if($hostName){
if($recType=='')$recType="MX";
exec("nslookup -type=$recType $hostName",$result);
foreach($result as $line){
if(preg_match("/^$hostName/",$line)){
return true;
}
}
return false;
}
return false;
}
public function checkErrors(){
if(count($this->errors)>0){
return true;
}
return false;
}
public function displayErrors(){
$output='<ul>';
foreach($this->errors as $error){
$output.='<li>'.$error.'</li>';
}
output.='</ul>';
return $output;
}
}
?>
All right, the two files listed above are all that you need to have a fully-functional form validation system that works in both the client and the server. My final recommendation is that you modify of the JavaScript functions that check form data in the client in such a way that they suit your specific requirements.
Final thoughts
Unfortunately, this educational journey has ended. However, the experience has been instructive, since you’ve learned how to create not only a client-based form validation application that uses the DOM for displaying the corresponding error messages in the web document, but how to integrate the system with a handy PHP 5 class. With such a huge amount of code to play with, fun is already guaranteed.
See you in the next PHP series!
| DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |