Forgot Password?

  • Home
  • Resources
    • Blog
    • News
    • Professional services
  • Projects
    • Webber
    • WB Ticket System
    • WB Blog
  • Contact
  • Support
    • Wiki
    • Forum
    • Ticket system

DrSoft Blog

sharing thoughts, ideas...

  • Tags

    • css
    • galleries
    • drsoft
    • webber
    • open source
    • applications
    • developers
    • Webber
    • protection
    • guide
    • files
    • mod_rewrite
    • downloads
    • hotlinking
    • htaccess
    • leechers
    • menu
    • programming
    • plugins
    • ajax
    • form validation
    • jquery
    • php
    • ide
    • editors
    • progress bar css php
    • modules
    • blog
    • speedy
    • codeigniter
    • buttons
    • html
    • email
    • phpmailer
    • sendmail
    • smtp
    • validation. user friendly
    • file upload
    • multiple
    • login
    • secure

PHP Validation done right Posted on 28-09-09, 09:47 PM by blog 0

Building forms is a pain for every programmer. The way you build them affects your user's experience and whatever has an impact on that is quite important. People hate filling forms as much as we hate building them. The process must be very straightforward and as friendly as possible otherwise the impact might affect your sales or whatever it is that you're looking to collect when building your form. In this tutorial we will try to track down the bottlenecks of a PHP form and find solutions to avoid them as much as possible in order to cut down the time required for our users to complete our forms and also follow our requirements or validators, however you want to call them.

A good form validation is done both on the client side and on the server side. Client side means that the validation is done in the browser using javascript. The advantage is that the form is not submitted, the page is not refreshed and the response is instant. The disadvantage is that you cannot perform complex validations or your client can simply turn off the javascript and all the magic is gone so it requires a backup plan on the server.

Since the tutorial is about PHP validation we're going to focus on the server side validation and learn how to build and validate user friendly web forms in PHP.

First, we need to make a list with things that we hate most when filling out forms:
- general errors ("Your information is not valid, please try again")
- the form does not remember my input after submitting it and I have to re-fill
- I don't know what's required or not
- all errors in a sigle place, usually at the top, causing me to ping-pong my eyes especially if I have a long form to fill
- errors like the above general one but also telling me to go back and try again

Now that we now what stresses people most, we need to address each and every one of them to make sure we're not doing these mistakes in our applications. Many programmers simply validate each field at each form in part the standard way but we're going to be smarter and make use of re-usable code. We're going to build a PHP class which can be instanciated in any place. Our scenario is actually built using 2 classes, one for the validation wich does the logic and the other holds the validators which consists of static methods just to perform the field validation and return boolean values like TRUE for passed, FALSE for failed.

The validation class is also supposed to store errors for each field in part in order to display them next to the field and nowhere else. This way is easier for our visitors to address them since the error message sites right next to the input. It also has to be smart enough and remember the values already posted by our visitor to avoid forcing him to re-fill all the inputs until everything is as requested by our validation scenario.

So, the form is submitted, the information is sent via POST and the server receives it. At that point, we instanciate our validation class and add all the validations to each field in part to make sure that what we receive and pass to further actions is the kind of data we expect. That's the whole point of a form validation anyways. Forcing people to submit what we expect making sure we don't encounter any errors.

We added the validation rules and next, we need to perform the validation itself, if any of the fields fail the validation, we stop the execution and present the form once again along with the errors marked in a nice red color. Once everything is received as we want and processed (database, email etc), we redirect the visitor to a success page and hide the form as we don't need it any more. This is what our target should be, a fast, smart and straightforward process for our visitors.

require_once "validation.php";

//	instanciate the validation class
$validation = new Validation;

//	subject validation rules
$validation->addField ( 'subject', 'required', 'This field is required' );
$validation->addField ( 'subject', 'min_length[5]', 'Your subject must contain at least 5 characters' );
$validation->addField ( 'subject', 'max_length[255]', 'Your subject must not contain more than 255 characters' );

//	name validation rules
$validation->addField ( 'name', 'required', 'This field is required' );
$validation->addField ( 'name', 'min_length[5]', 'Your name must contain at least 5 characters' );
$validation->addField ( 'name', 'max_length[255]', 'Your name must not contain more than 255 characters' );

//	email validation rules
$validation->addField ( 'email', 'required', 'This field is required' );
$validation->addField ( 'email', 'validEmail', 'Please add a valid email' );

//	message validation rules
$validation->addField ( 'message', 'required', 'This field is required' );
$validation->addField ( 'message', 'min_length[20]', 'Your message must contain at least 20 characters' );
$validation->addField ( 'message', 'max_length[2000]', 'Your message must not contain more than 2000 characters' );

//	execute the validation
if ( $validation->execute () ) {
	//	success, send the email, save the data in the database etc.
	header ( "Location: success.php" );
}

//	if we're here, the validation failed


As you can see, we can add unlimited validations to one field in part, each of them with a custom error message. This allows us to communicate better with the end user by building a smart, user friendly PHP form. Thank you for reading this, don't forget to download the example located at the end of this tutorial.

Validator.zip Read more ...

Stunning ajax form validation Posted on 26-09-08, 05:52 AM by blog 0

Demo link | Download link

I always had this in mind but never really searched for a good solution or I wasn't determined enough to implement it in my work. When you're used to a certain type and method of working, as a programmer, you're not searching for new cool things and, instead, you tend to use and re-use what you already know. Ever since ajax came out and revolutionized the web and user experience most important I tried to know every little secret of it. Tried all the libraries and cool effects, followed a lot of tutorials and played with many examples but never started a project with ajax on the plan from the very start.

In this tutorial we will build a very nice form with ajax posting and validation. Our form will also change the css classes of the inputs, display validation errors and all that sexy stuff which is meant to help our visitor better identify what was filled wrong and what needs to be done in order to successfully submit the form.

For this example I decided to use jQuery which is a fantastic, easy to use, javascript library. The form we're using in this tutorial is a simple register form with 4 basic fields: username, password, password again and email address. On form submit we will use ajax to collect the info, send it to a page and analyze the response which is sent back. Also, I've set the onsubmit="return false;" action for the form in order to stay in the same page and take advantage of the beauty of ajax.

Let's start with a simple ajax function to submit the form:

function ajax_form(form,site_url,link_id){
	var req = jQuery.post
	( 
		site_url, 
		jQuery('#' + form).serialize(), 
		function(html){
			jQuery('#' + link_id).html(html);
			req = null;
		}
	);
}

This function grabs the submitted form info, send it via post to a given page and injects the response message in some element of choice (div,table,span etc). It needs 3 parameters: form = the id of the form being submitted site_url = the url of the page that we're posting at link_id = the id of the element where you wish to inject the response message (in our case, I placed a div with the id "receiver" just above the form"

Ok. Everything's fine until now when the question comes: how should I perform the validation, how should I point the user to the right place if the validation fails. We need something nice and visual. Every input has a gray border of 1 pixel around it. The input's border where the info was wrong or not filled will become red making it very easy to identify. Needless to say that there are thousands of websites which simply throw an error like "Form validation failed! Please try again" and you're left searching the error in a form of 20 inputs. That's a pain and we're going to solve it from the first step by adding a red border around the those inputs.

The scenario is simple, you submit, the next page receives the data and validates it. If something wrong is found it will be added to an array. For each input in part the validation will either come with an ok or an error in front of the response message. Here's an example: 'error|username|Please fill in your username' where: error = the response status for that input username = the id of the input Please fill in your username = the response message/validation error

Every response comes in a new line and you can add as many validations you need for a single input. This is very important.

Let's take a look at the validation page:

if ( empty ( $_POST [ 'username' ] ) )
{
	$errors [ 'username' ] [] = "Please enter your username\n";
}

if ( empty ( $_POST [ 'password' ] ) )
{
	$errors [ 'password' ] [] = "Please enter your password\n";
}

if ( empty ( $_POST [ 'password_confirmed' ] ) )
{
	$errors [ 'password_confirmed' ] [] = "Please enter your password again\n";
}

As you can see, in case of an error, the field is represented by an array to hold the messages.

After this, the validation page will do a foreach on the $_POST array (for every input in part) and build the response in order to return html. Each message will be printed on a new line in the response which explains the "\n" sign at the end of the validation message.

It's time to switch back to our javascript code and see how to interpret this type of response. First of all, we will split the response message by the new line.

var explode = html.split("\n");

We now have a javascript array with the validation messages. We will loop through them so that we can identify the inputs with errors.

for ( var i in explode )
{
	var explode_again = explode[i].split("|");
}

As you can see, we're using another split in the loop. This one is to identify the id of the input, the type of message and the validation message/instruction.

explode_again[0] = the type of message (error, success) explode_again[1] = the id of the input explode_again[2] = the validation message

We're going to extend the loop above and start adding css classes to those inputs:

for ( var i in explode )
{
	var explode_again = explode[i].split("|");
	jQuery('#' + explode_again[1]).addClass('error');
}

Looking at the css class called .error you will see that it adds the red border mentioned above.

Perfect...but we're not finished. I also want to add a green border to the inputs which passed the validation (this is why the first element in the response message was added). If the visitor enters the right details after failing a submit, we will have to revalidate and assign the right classes to make that input green from red and indicate to the user that the new info fixed the error.

To avoid a conflict between classes or using too much repeating code over and over again we will create a javascript function to add/remove the right classes:

function add_remove_class(search,replace,element_id)
{
	if (jQuery('#' + element_id).hasClass(search)){
		jQuery('#' + element_id).removeClass(search);
	}
	jQuery('#' + element_id).addClass(replace);
}

where: search = the class to be removed replace = the class to be added elemeny_id = the input or any other element with an id

The demo contains a little more than what we discussed here but it's enough for you to get started and implement this type of validation.

Demo link | Download link Read more ...
Home
© 2008 drSoft Ltd. All rights reserved.