Blog Post RSS ?

Blogs » PHP » Validation with CType
 

Validation with CType

by Harry Fuecks

What happens when you take you eye off the ball? The CType extension becomes a default part of PHP!

Have to confess I’ve never touched them until recently and was stuck in a “validation = regular expressions” mindset. What puzzles me is I haven’t seen anyone else using them either – most libraries doing some validation, including QuickForm and Validate all use regular expressions. Anyone know why? It’s not hard to use them but fall back to regular expressions for older PHP versions.

The CType functions are wrappers for ctype.h, a standard part of C, so are, effectively, very well tested.

The point is, for validating certain basic types of data, they do a better job than regular expressions, being both faster and supporting international character sets. The also make your code more “declarative” in nature – it’s pretty clear what ctype_digit() does while ‘/(^-?\d\d*\.\d*$)|(^-?\d\d*$)|(^-?\.\d\d*$)/’ is less obvious.

For example say you have a field in your form for “First Name”. Using regular expressions, you’d probably validate it something like;

if ( !preg_match('/^[a-zA-Z]*$/', $first_name) ) { die ('Alpha characters only please!'); }

Now that’s fine if your name is Joe but what if your name is Håvard?

By using a function like ctype_alpha(), you can perform a basic check like;

if ( !ctype_alpha($first_name) || strlen ($first_name) == 0 ) { die ('Alpha characters only please!'); }

My guess is on most systems Håvard will now be able to enter his name as is. If not you’ll need to resort to setlocale().

Big Word of Warning!: the ctype functions will validate empty strings as being valid. Make sure you check the length as well!

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • Ping.fm
  • Twitthis

Related posts:

  1. W3C Markup Validation Service adds experimental HTML5 support A few days ago, the W3C added experimental support for...
  2. 10 Things to Check Before Using a CAPTCHA Hacking attempts and spam bots are your problem - not...

This post has 12 responses so far

Sponsored Links

SitePoint Marketplace

Buy and sell Websites, templates, domain names, hosting, graphics and more.

Follow SitePoint on...