You are here: HomeForums » PHP » PHP Coding » Simple function for string validation

Simple function for string validation (1 post)

in Forums » PHP » PHP Coding
  • Started 1 month ago by thdadmin

thdadmin (administrator)

Hi! Here is a very robust functions that help you validate certain strings. It doesn't use regular expressions. It uses two parameters. The first is the string that needs validation, and the second is the string of allowed characters. The function checks for characters that are not present in second parameter and if so returns false.
Here's the code:

function is_valid($string, $allowed_chars) {
  $l = strlen($string); // the lenght of the string
  for ($i = 0; $i < $n; $i++) { // for every characters in $string
  if (strpos($allowed, $string{$i}) === false) { // check if character is valid
      return false; // string is invalid
    } else {
      continue;
    }
  }
  return true; // string is valid
}

You can use this function in many ways. For example, to verify if the string is an interger, call the function this way:

is_valid($integer, '1234567890');

One problem occurs when you need to validate a floating-point number. The '.' needs to appear in the second parameter, like so:

is_valid($float_num, '1234567890.');

but it also returns true if multiple instances of decimal point appear.
You can expand this function or create new ones for validating float type. Post you function below. If you have any questions, go ahead!

Posted 1 month ago #

Reply

You must log in to post.