G2VALID › An Easy PHP Form Validation Class

Are you among the web developers who struggles with form validation like i did ? tired of nesting if statements ? well here is a solution if you are using PHP.

Let me introduce you to G2VALID. An Easy PHP Form Validation Class to make your life much easier and saves you plenty of time. This class uses OOP PHP so its much easier to use and manage on your projects.

See also : Trends to Focus on When Designing a Tablet Friendly Website

// ————————————————————————————————————|
This validation class requries php 5.0 onwards and few filtering options require C_TYPE |
enabled php configuration. If you are not sure about what this C_TYPE is, contact your |
hosting provider to check if it’s enabled, view your php info for ctype functions. This is usually |
turned on so nothing much to worry. ( tested on hostgator ) //
—————————————————————————————————————-

Okay so lets see what type validation options are available in the alpha stage for us to use. i’m going to be include the method names along with these for easy reference.

Checks for empty input
	|	isEmpty($param) 		|	(@param | String : custom error message)
Checks for valid email
	|	validEmail($param) 	|	(@param | String : custom error message)
Checks for valid URL according to http://www.faqs.org/rfcs/rfc2396
	|	validURL($param) 		|	(@param | String : custom error message)
Checks if the $field is the same as the instace field ( used for password field matching )
	|	isSame($field,$error)	
	|	(@$field  | String : field to be compared with)	|	 (@error   | String : custom error message)
	| 	Ex Use : ->field('passwd')->isSame('passConfirm','Didnt Match');
Checks for valid Ip Address
	|	validIP($param) 		|	(@param : custom error message)
Check for Minimum Length of a string
	|	minLength($min,$error)
	|	($min     | int : the minimum string size)
	|	 (@error   | String : custom error message)
Check for Maximum Length of a string
	|	maxLength($max,$error)
	|	($max     | int : the minimum string size)
	|	(@error   | String : custom error message)
Checks for A-Za-z and space
	|	alpha($param)  		|	(@param | String : custom error message)
Checks for A-Za-z 0-9
	|	alphanumeric($param) 	|	(@param | String : custom error message)
Checks for an valid int
	|	isInt($param)		|	(@param | String : custom error message)
Checks for an valid float
	|	isFloat($param)		|	(@param | String : custom error message) 

Now that you know what options available for use, lets simulate a simple form validation.

See, its simple as that and you are good to go. . please also note that sendEmail(); function used their is for dummy purposes. you can replace it with what ever code you want. The demo above only displayed few possibilities of the the class, lets dig in deeper to see whats available for us to use

Now that you know how easy it is to validate a form, lets dig in deeper to find out what types of reporting is avalible for validations.

1- Get all Errors of a field as array (@return array)

This wil return all the errors of a specific field as an array when more than 1 validation rule is set

Validation  : $instance->field('username')->isEmpty()->minLength(5)->maxLength(10);
Get Errors  : $instance->>field('username')->getErrorsAsArray()

2- Get Error of a field (@return string)

Get the error of a field, if multiple validation rules are set, the 1st error occurrence will be returned and also note that by setting getError(true) will return a detailed output with the error message and field name.

Validation  : $instance->field('username')->isEmpty('Enter a username');
Get Errors  : $instance->>field('username')->getError()

3- Get all Errors of a field as a string (@return string)

This wil return all the errors of a specific field as a string if multiple validation rules are set, also note that by setting getErrorAsString(true) will output the field names along with the error

Validation  : $instance->field('website')->isEmpty()->validURL();
Get Errors  : $instance->>field('website')->getErrorAsString()

4- Get all Errors of the form or instance (@return array)

This might be good for debugging or if you plan to take validation to the next level, this will return all the errors of the instance as an array

Validation
----------
$instance->field('website')->isEmpty('Web site is required')->validURL('Enter Valid Website');
$instance->field('username')->isEmpty('username is required')->minLength(5)->maxLength(10);
$instance->field('email')->isEmpty('email is required')->validEmail('Enter Valid Email');

All errors are stored in the object it self
-----------------------------------------------------
$instance;

// To simply inspect, you can use
print_r($instance);

5- Get all Errors of the form or instance (@return string)

This is very useful if you want to report all the errors of the form at once as a string,It’s always easy right ?. if you haven’t set custom error messages, pass the additional parameter true to turn on detailed reporting like in example below

Validation
----------
$instance->field('website')->isEmpty()->validURL();
$instance->field('username')->isEmpty()->minLength(5)->maxLength(10);
$instance->field('email')->isEmpty()->validEmail();

All errors of instance as a string with detaild reporting
------------------------------------------------------------------------
echo $instance->getErrorAsString(true);

Now in some of the forms i have set custom field names, but in some cases i haven’t, in order to make sure the user gets a better understanding of whats going on, you can always turn on detailed reporting for each method if your aren’t specifying custom error messages.

You can do this by adding an extra parameter (true) to error reporting methods to get an detailed report.

getErrorAsString(true);
getError(true);

Did you expect this amount of reporting options ? i guess you never did but here you go. Now you know that weather its get or post, you can validate the form. But do you only require validations for forms ? you often grab data from databases, external API’s and etc… We know its not only the form fields ( GET & POST ) which should be validated, other stuff exists too. Don’t worry, G2 Valid has just the right options for you. So lets see how we can dynamically Do Stuff by creating a dynamic field, this code will be a continuation from the basic demo [https://github.com/dsginvilla/G2Valid#basic-demo] So lets begin by creating a new field

Adding the dynamic field by using addField() method
$validator->addField('db_id');

/* 
	We use setValue() method to add or change values of an exisitng field.
	$db->getId()  | this is for demonstration purposes only, lets imagine this extracts an
	ID of a record form the database based on the session username or something.
*/
$validator->field('db_id')->setValue($db->getId());

/* 
	Without using multiple lines, you can do it in a single line, fancy right ?
*/
$validator->addField('db_id')->setValue($db->getId())->isEmpty('No Db record')->isInt('Invalid id');

Now that you have seen what this can do, i’m ready to show you a complete demo, not just dummy code but a working solution. you are welcome to download the sample project and check out the source 😉

Download