administration mode

 

Code Igniters' form validation brilliance »

FERDY CHRISTANT - JUL 26, 2008 (11:42:58 AM)

I know I keep rambling about how great the Code Igniter PHP MVC framework is, but I just keep finding new gems inside it. I was on my way to start coding for the Jungle Dragon project.I decided to first work on the user registration form, as pretty much everything in the project evolves around users. The registration form is similar to those of other sites:

  • User must supply a username, password, and email. They must type the password and email twice and they need to match the first field. The username must not already exist, have a minimum number of characters and contain allowed characters only. The email address must be in a valid format. There are also check on the maximum amount of characters per field.
  • Next, there is a list of optional fields
  • Finally, the user must check that they agree with the Terms of Use.
  • Should any validation fail, the user's initial values are not lost, the form is simply updated with specific error messages per field.

Easy enough, right? True, this is easy, but you would be surprised at the amount of validation code the above scenario would produce without any help.To be specific, we're talking about 23 validation rules for just 5 technical fields, and only 3 functional fields. That's a whole lot of if statements!

Luckily, help is around the corner. Code Igniter has a Validation class that bring down the amount of code for the above scenario to this:

There's only some slight additional plumbing code to be done in order to customize error messages but it's all easy. Note that I have also configured Code Ingiter to automatically apply XSS filtering on all posted values.

Another interesting feature is the callback mechanism. Code Igniter obviously has no way to know how it should check if a user already exists in the database. In those cases, one can simply write a custom function that resolves to true or false and sets the custom error message. Next, you refer to this custom function in the rule definition.

This just saved me many hours, as Code Igniter has done already.

BOOKMARK THIS CONTENT
del.icio.us technorati digg Furl YahooMyWeb Reddit NewsVine
RATE THIS CONTENT (OPTIONAL)
Was this document useful to you?
 
rating Awesome
rating Good
rating Average
rating Poor
rating Useless
CREATE A NEW COMMENT
required field
required field HTML is not allowed. Hyperlinks will automatically be converted.
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30