<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Jason Ashdown &#187; Validation</title>
	<atom:link href="http://www.jasonashdown.co.uk/tag/validation/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.jasonashdown.co.uk</link>
	<description>There&#039;s no place like 127.0.0.1</description>
	<lastBuildDate>Thu, 22 Dec 2011 11:40:13 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
<xhtml:meta xmlns:xhtml="http://www.w3.org/1999/xhtml" name="robots" content="noindex" />
		<item>
		<title>PHP Validation Class for Forms</title>
		<link>http://www.jasonashdown.co.uk/2008/08/php-validation-class-for-forms/</link>
		<comments>http://www.jasonashdown.co.uk/2008/08/php-validation-class-for-forms/#comments</comments>
		<pubDate>Fri, 01 Aug 2008 22:50:52 +0000</pubDate>
		<dc:creator>Jason Ashdown</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Web Development]]></category>
		<category><![CDATA[Forms]]></category>
		<category><![CDATA[Validation]]></category>

		<guid isPermaLink="false">http://www.jasonashdown.co.uk/?p=27</guid>
		<description><![CDATA[Just to top off my daily posts, I have been perfecting a PHP Validation class over the past few months. At work I tend to do a lot of registration forms for competitions, subscriptions, newsletters, contact forms etc. So I &#8230; <a href="http://www.jasonashdown.co.uk/2008/08/php-validation-class-for-forms/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Just to top off my daily posts, I have been perfecting a PHP Validation class over the past few months.</p>
<p>At work I tend to do a lot of registration forms for competitions, subscriptions, newsletters, contact forms etc.</p>
<p>So I went to the trouble of creating a very quick and easy validation class that I could include into my projects at a drop of a hat. Inspired by <a title="CodeIgniter, PHP framework" href="http://codeigniter.com" target="_blank">CodeIgniters</a> validation class, it has very similar features. Including helper functions.</p>
<p>It&#8217;s even UTF-8 friendly (except for the email function). Please feel free to <a href="http://www.jasonashdown.co.uk/downloads/validation-0.2j.zip">download</a> and test it out yourself.<span id="more-27"></span></p>
<p>Here is a dump of the code:</p>
<pre class="brush: php; title: ; notranslate">
&lt;?php
/************************************************************
  Validation Class
  Author: Jason Ashdown
  Updated: 12:12 24/07/2008
  Version 0.2j

 --------------------------------------------------------
 Change Log:-
 v0.2j - Added 'decode' function to form helpers. To help
		 pass UTF-8 characters back to a form from the DB.
 v0.2h - Removed 'spaces' from the regexp strings
 v0.2g - Email address function is now in compliant
		 with RFC 2822
 v0.2f - Added $masks for allErrors to be more
		 user-friendly, updated loop_clean to use
		 htmlspecialchars and supports UTF-8
 v0.2e - Fixed allErrors() to include wrappers
 v0.2d - Changed &quot;required&quot; to check for empty
		 strings properly
 v0.2c - Added &quot;not_equal&quot; and &quot;selected&quot; functions
 v0.2b - Tidied comments; fixed email mx check
 v0.2a - Added loop_clean (multi-array sanitiser)
 V0.2 - Added new helper functions (label, check)
 - - -
 v0.1 - Initial Release
*************************************************************/

class validateForm
{
	var $input = array();
	var $error = array();
	var $error_wrapper;
	var $pass;

	// You can call the validated inputs directly from this class
	// when you come to inserting them into the db, e.g.
	// $form = new validateForm($_POST);
	// $form-&gt;input['fullname']; etc...

	function validateForm($input=array()) // Yes, post the the whole $_POST/$_GET array into the function
	{
		$this-&gt;input = $input; // Clone form inputs array into here

		$this-&gt;pass = true; // Flag changes if theres an error

		// Config
		$this-&gt;error_wrapper['start'] = &quot;&lt;br /&gt;&lt;span class=\&quot;error\&quot;&gt;&quot;;
		$this-&gt;error_wrapper['end'] = &quot;&lt;/span&gt;&quot;;

		// Sanitise our arrays
		$this-&gt;loop_clean($this-&gt;input);
	}

	//
	// We can even perform some security checks here if we wish
	//
	function loop_clean(&amp;$data)
	{
		foreach ($data as $key =&gt; $value)
		{
			if ( !is_array($value) )
			{
				// Well formatted string; PHP4 requires &quot;stripslashes&quot; on all input fields
				$data[$key] = trim(htmlspecialchars(strip_tags(stripslashes($value)), ENT_QUOTES, 'UTF-8'));
			}
			else
			{
				$this-&gt;loop_clean($value);
				$data[$key] = $value;
			}
		}
	}

/************************************/
/* Error Functions                  */
/************************************/

	// Set error
	function error($item, $desc)
	{
		$this-&gt;pass = false;
		$this-&gt;error[$item] .= $desc.&quot; &quot;; // Append multiple error messages
	}

	// Return the error
	function showError($item)
	{
		return $this-&gt;error_wrapper['start'].trim($this-&gt;error[$item]).$this-&gt;error_wrapper['end'];
	}

	function allErrors($masks=array())
	{
		foreach ( $this-&gt;error as $key =&gt; $value )
		{
			// Mask field names with more appropriate User friendly names
			$key = $masks[$key] != '' ? $masks[$key] : $key;
			echo $this-&gt;error_wrapper['start'].&quot;&lt;b&gt;&quot;.ucfirst($key).&quot;&lt;/b&gt;: &quot;.trim($value).$this-&gt;error_wrapper['end'];
		}
	}

/************************************/
/* Debugging                        */
/************************************/

	function showInputs()
	{
		print_r($this-&gt;input);
	}

/************************************/
/* Validation Functions             */
/************************************/

	function not_equal($string, $field)
	{
		if ( is_string($string) )
		{
			if ($string == $this-&gt;input[$field])
			{
				$msg = &quot;You must select a different option other than \&quot;$string\&quot;&quot;;
				$this-&gt;error($field, $msg);
				return false;
			}
			return true;
		}
		return false;
	}

	function min_length($min=0, $field)
	{
		if( strlen($this-&gt;input[$field]) &lt; (int) $min )
		{
			$msg = &quot;This field cannot be shorter than $min characters.&quot;;
			$this-&gt;error($field, $msg);
			return false;
		}
		return true;
	}

	function max_length($max=0, $field)
	{
		if ( strlen($this-&gt;input[$field]) &gt; (int) $max )
		{
			$msg = &quot;This field cannot be longer than $max characters.&quot;;
			$this-&gt;error($field, $msg);
			return false;
		}
		return true;
	}

	function alpha($field)
	{
		if ( !preg_match(&quot;/^([a-z])+$/i&quot;, $this-&gt;input[$field]) )
		{
			$msg = &quot;This field can only contain letters (A-Z). No foreign characters allowed.&quot;;
			$this-&gt;error($field, $msg);
			return false;
		}
		return true;
	}

	// Double-barrel names and marital status will require this
	function alpha_dotdash($field)
	{
		if ( !preg_match(&quot;/^([a-z\-\.])+$/i&quot;, $this-&gt;input[$field]) )
		{
			$msg = &quot;This field can only contain characters (A-Z-.). No foreign characters allowed.&quot;;
			$this-&gt;error($field, $msg);
			return false;
		}
		return true;
	}

	// Useful for Addresses or fields that may contain unusual but still valid chars
	function alpha_special($field)
	{
		if ( !preg_match(&quot;/^([a-z0-9\-+\.,_='\&quot;@#])+$/i&quot;, $this-&gt;input[$field]) )
		{
			$msg = &quot;This field has illegal characters. You can use letters, numbers and (._-+='\&quot;@#).&quot;;
			$this-&gt;error($field, $msg);
			return false;
		}
		return true;
	}

	function numeric($field)
	{
		if ( !preg_match(&quot;/^[\-+]?[0-9]*\.?[0-9]+$/&quot;, $this-&gt;input[$field]) )
		{
			$msg = &quot;This field must contain only numbers.&quot;;
			$this-&gt;error($field, $msg);
			return false;
		}
		return true;
	}

	function alpha_numeric($field)
	{
		if( !preg_match(&quot;/^([a-z0-9])+$/i&quot;, $this-&gt;input[$field]) )
		{
			$msg = &quot;This field can only contain letters and numbers.&quot;;
			$this-&gt;error($field, $msg);
			return false;
		}
		return true;
	}

	function required($field)
	{
		if ( !isset($this-&gt;input[$field]) OR $this-&gt;input[$field] == '' )
		{
			$this-&gt;error($field, 'This field is required.');
			return false;
		}
		elseif ( is_array($this-&gt;input[$field]) )
		{
			$this-&gt;error($field, 'This is an array and won\'t be passed.');
			return false;
		}
		return true;
	}

/************************************/
/* Alias Functions                  */
/************************************/

	function fullname($field, $req=true)
	{
		if ( $req == true AND !$this-&gt;required($field) )
			return false;

		return $this-&gt;alpha_dotdash($field);
	}

	function address($field, $req=true)
	{
		if ( $req == true AND !$this-&gt;required($field) )
			return false;

		return $this-&gt;alpha_special($field);
	}

	function telephone($field, $req=true)
	{
		if ( $req == true AND !$this-&gt;required($field) )
			return false;

		if ( $this-&gt;numeric($field) AND $this-&gt;min_length(11, $field) AND $this-&gt;max_length(14, $field) )
		{
			return true;
		}

		return false;
	}

	function mobile($field, $req=true)
	{
		if ( $req == true AND !$this-&gt;required($field) )
			return false;

		return $this-&gt;telephone($field);
	}

	function postcode($field, $req=true)
	{
		if ( $req == true AND !$this-&gt;required($field) )
			return false;

		if ( !preg_match(&quot;/^[a-zA-Z]{1,3}[0-9]{1,3} [0-9]{1}[a-zA-Z]{2}$/i&quot;, $this-&gt;input[$field]) )
		{
			$msg = &quot;Postcode must follow the format of \&quot;XX1 1XX\&quot;.&quot;;
			$this-&gt;error($field, $msg);
			return false;
		}
		return true;
	}

	function email($field, $req=true, $mx_records=false)
	{
		if ( $req == true AND !$this-&gt;required($field) )
			return false;

		// Function from: http://www.ilovejackdaniels.com/php/email-address-validation/
		// Complies with the email address specification guidelines: RFC 2822

		// First, we check that there's one @ symbol, and that the lengths are right
		if (!ereg(&quot;^[^@]{1,64}@[^@]{1,255}$&quot;, $this-&gt;input[$field]))
		{
			// Email invalid because wrong number of characters in one section, or wrong number of @ symbols.
			$msg = &quot;Your email address is the wrong length.&quot;;
			$this-&gt;error($field, $msg);
			return false;
		}

		// Split it into sections to make life easier
		$email_array = explode(&quot;@&quot;, $this-&gt;input[$field]);
		$local_array = explode(&quot;.&quot;, $email_array[0]);

		for ($i = 0; $i &lt; sizeof($local_array); $i++)
		{
			if (!ereg(&quot;^(([A-Za-z0-9!#$%&amp;amp;amp;amp;amp;'*+/=?^_`{|}~-][A-Za-z0-9!#$%&amp;amp;amp;amp;amp;'*+/=?^_`{|}~\.-]{0,63})|(\&quot;[^(\\|\&quot;)]{0,62}\&quot;))$&quot;, $local_array[$i]))
			{
				$msg = &quot;The first part of your email is malformed.&quot;;
				$this-&gt;error($field, $msg);
				return false;
			}
		}

		if (!ereg(&quot;^\[?[0-9\.]+\]?$&quot;, $email_array[1])) // Check if domain is IP. If not, it should be valid domain name
		{
			$domain_array = explode(&quot;.&quot;, $email_array[1]);
			if (sizeof($domain_array) &lt; 2)
			{
				$msg = &quot;Your email doesn't have a valid domain.&quot;;
				$this-&gt;error($field, $msg);
				return false; // Not enough parts to domain
			}

			for ($i = 0; $i &lt; sizeof($domain_array); $i++)
			{
				if (!ereg(&quot;^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]+))$&quot;, $domain_array[$i]))
				{
					$msg = &quot;Your email doesn't have a valid domain.&quot;;
					$this-&gt;error($field, $msg);
					return false;
				}
			}
		}

		// Check online to see if this is a real email host!
		if ( $mx_records != false )
		{
			$host = $email_array[1]; //The whooole domain

			getmxrr($host, $mxhosts);
			if ( count($mxhosts) &lt; 1 )
			{
				$msg = &quot;There is no email host associated with your email. This probably means its fake.&quot;;
				$this-&gt;error($field, $msg);
				return false;
			}
		}

		return true;
	}

/************************************/
/* Helper Functions                 */
/************************************/

	function decode($field)
	{
		return html_entity_decode($this-&gt;input[$field]);
	}

	function label($text, $id)
	{
		return &quot;&lt;label for=\&quot;$id\&quot;&gt;$text&lt;/label&gt;&quot;;
	}

	function check($field, $value, $default=false)
	{
		if ( $default == true AND empty($this-&gt;input[$field]) )
			return 'checked=&quot;checked&quot;';

		return $this-&gt;input[$field] == $value ? 'checked=&quot;checked&quot;' : '';
	}

	function selected($field, $value, $default=false)
	{
		if ( $default == true AND empty($this-&gt;input[$field]) )
			return 'selected=&quot;selected&quot;';

		return $this-&gt;input[$field] == $value ? 'selected=&quot;selected&quot;' : '';
	}
}

/*
Example:

You can just edit $this-&gt;error_wrapper['start'] AND $this-&gt;error_wrapper['end'] to make the errors display how you want.
*/

if ( $_SERVER['REQUEST_METHOD'] == 'POST' )
{
	$form = new validateForm($_POST);

	$form-&gt;required('firstname');
	$form-&gt;required('lastname');
	$form-&gt;mobile('mobile');
	$form-&gt;email('email', true); // Validate email AND make it required
	$form-&gt;required('t-and-c'); // Terms &amp;amp;amp;amp;amp; Conditions

	if ( $form-&gt;pass == true )
	{
		// Insert data into DB ...
		echo &quot;Success&quot;;
	}
}
else
{
	$form = new validateForm();
}
?&gt;

&lt;div class=&quot;error&quot;&gt;
&lt;?php

// Masks are used if you have an unfriendly named field that may cause the user confusion.
// You just specify the names and the fields in the array with the text you want to replace it with.
$masks = array(
't-and-c' =&gt; 'Terms &amp;amp;amp;amp;amp; Conditions');

$form-&gt;allErrors($masks);
?&gt;
&lt;/div&gt;

&lt;form method=&quot;post&quot;&gt;

&lt;p&gt;*First Name: &lt;input type=&quot;text&quot; name=&quot;firstname&quot; value=&quot;&lt;?php echo $form-&gt;input['firstname'];?&gt;&quot; maxlength=&quot;80&quot; /&gt;
&lt;?php
// Show inidividual errors
echo $form-&gt;showError('firstname');
?&gt;
&lt;/p&gt;

&lt;p&gt;*Last Name: &lt;input type=&quot;text&quot; name=&quot;lastname&quot; value=&quot;&lt;?php echo $form-&gt;input['lastname'];?&gt;&quot; maxlength=&quot;80&quot; /&gt;&lt;/p&gt;
&lt;?php
// OR Specify your own error message
if ( $form-&gt;showError('lastname') )
{
	echo 'You must fill in the &quot;Last Name&quot; field.';
}
?&gt;

&lt;p&gt;Mobile: &lt;input type=&quot;text&quot; name=&quot;mobile&quot; value=&quot;&lt;?php echo $form-&gt;input['mobile'];?&gt;&quot; /&gt;&lt;/p&gt;

&lt;p&gt;*Email: &lt;input type=&quot;text&quot; name=&quot;email&quot; value=&quot;&lt;?php echo $form-&gt;input['email'];?&gt;&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Comment: &lt;textarea name=&quot;comment&quot;&gt;
&lt; ?php
// If you ever send data that has UTF-8 in it, you can use the decode helper if retrieving it from a DB
echo $form-&gt;decode('comment');

?&gt;&lt;/textarea&gt;&lt;/p&gt;

&lt;p&gt;&lt;input type=&quot;checkbox&quot; name=&quot;t-and-c&quot; id=&quot;t-and-c&quot; value=&quot;true&quot; &lt;?php echo $form-&gt;check('t-and-c', true);?&gt;/&gt; &lt;?php echo $form-&gt;label('Terms and Conditions*' ,'t-and-c');?&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;* Required&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;input type=&quot;submit&quot; value=&quot;Send&quot; /&gt;&lt;/p&gt;

&lt;/form&gt;
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.jasonashdown.co.uk/2008/08/php-validation-class-for-forms/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
	</channel>
</rss>

