Simple string validation with PHP

A question from Yahoo! Answers:

I have googled, forummed, read the manual and I am still unable to accomplish or properly understand form validation.

I use dreamweaver, php4 and mysql. My site depends on user input, mostly text.
I want to validate the input as text plus punctuation only, input to database or redirect to original form page with error messages.
I am having trouble making even the simplest validation using preg_match and simple regex to perform as expected, even when using a form and error page to practise.

For simple validation, you do not necessarily need regular expressions. Try this:

function isValid ($string) {
  $allowed = 'string containing all allowed characters';
  $n = strlen($string);
  for ($i = 0; $i < $n; $i++) {
  if (strpos($allowed, $string{$i}) === false) {
      return false;
    } else {
      continue;
    }
  }
  return true;
}

This is a simple function that would return TRUE if all characters in $string are found in $allowed and FALSE otherwise.

You can also slightly modify this function by making $allowed a second argument:

function isValid ($string, $allowed) {
  $n = strlen($string);
  for ($i = 0; $i < $n; $i++) {
  if (strpos($allowed, $string{$i}) === false) {
      return false;
    } else {
      continue;
    }
  }
  return true;
}

The advantage of doing so is that you can validate different things. For example, to validate an integer, you can call:

isValid ($toBeValidated, '1234567890')

To validate an alphanumeric string with punctuation, you can call something like this:

isValid ($toBeValidated, '1234567890' .
                         'ABCDEFGHIJKLMNOPQRSTUVWXYZ' .
                         'abcdefghijklmnopqrstuvwxyz' .
                         ' .,!?-;:()')

Obviously, you can expand the list of punctuation marks if you so choose…

Validating a floating-point number, however, may be problematic. You can call

isValid ($toBeValidated, '1234567890.')

but it will not guard against multiple instances of decimal point occurring in $toBeValidated, so you may need to check for it separately.

Leave a Reply

Your email address will not be published. Required fields are marked *