Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
KO3 Validation Module
PHP
branch: master

Fetching latest commit…

Cannot retrieve the latest commit at this time

Failed to load latest commit information.
classes
tests
README

README

<?php

//Basic Usage:

//1. Pass the data you want to validate to the validate class when you instantiate it.

$data = new Validate(array('username' => ' user123'));

//2. Add a filter to remove whitespace before validation is run.

$data->add_pre_filter(new Filter_Trim)
	 ->for_field('username');

//3. Add some validation to ensure only letters and numbers are contained in the username string.

$data->add_alpha_numeric_validation()
	 ->for_field('username')
	 ->with_message('The :label field can only contain letters and numbers.');
	
	/*
		The :label is the field name.  You can override the defualt by passing an optional array to the with_message method.
		Ex. with_message('The :label field can only contain letters and numbers.', array(':label' => 'new label name'));
	*/


//4. Add some validation to ensure that the username string is a minimum of three characters in length.

$data->add_min_length_validation(3) //pass the minimum number of characters to the add_min_length_validation method
	 ->for_field('username')
	 ->with_message('The :label field must be at :length characters.', array(':length' => 3));


//5. Run the validation on the data.

if ($data->check())
{
	echo "Success!";
}
else
{
	echo "Failure!?!";
	
	//get the error messages
	$errors = $data->get_errors();
}


/*
 * Extra: you can run certain validations on different events. This is a simple and incomplete example, but 
 * the basic flow is there.
 */

class User extends Model {
	
	
	public function check_username($username) 
	{
		return (in_array($username, $this->get_usernames())) ? TRUE : FALSE;
	}
	
	public function save() 
	{
		$data = new Validate(array('username' => ' user123'));

		//this will only run on the create event
		$data->add_callback_validation(array($this, 'check_username')) 
			 ->for_field('username')
			 ->with_message('The :label field must be unique.')
			 ->on('create');
		
		
		//if no on events are specified it will run on all events
		$data->add_min_length_validation(8) 
			 ->for_field('username')
			 ->with_message('The :label field must be at least :length characters in length.', array(':length' => 8));
		
			
		if ($this->is_new_record)
		{
			if ($data->check('create'))
			{
				$this->create($data);
			}
		}
		else
		{
			if ($data->check('update'))
			{
				$this->update($data);
			}
		}
		
		if ( ! $data->is_valid())
		{
			return $data->get_errors();
		}
	}
	
	
}



//5. Run the validation on the data.




?>
Something went wrong with that request. Please try again.