PHP validation functions

Hello my readers, after one month of hard work , i created a validation class and made a complete tutorial with 60 php validation methods in PHP. here each functions works independently. These methods are used in every kind of web applications. even i written the functions in PHP, you can use them in Javascript also by taking regular expression directly. If any method i missing ,fixing or you get idea for implementing and adding here please contact me.we can use this php class in form validation.

PHP validation functions

validation for alpha characters

Use: It validates only Alphabets i.e small and capital letters. Input parameter must be trimmed ,it won’t allow spaces also.

Regular Expression

/^([a-zA-Z])+$/i

Regular Expression has case insensitive modifier.

PHP function

   /**
     * Matches only alpha letters
     * @param   string   
     * @return  boolean
     */
    function is_alpha($val)
    {
        return (bool)preg_match("/^([a-zA-Z])+$/i", $val);   }

Valid parameters

  • Mahesh
  • chari
  • PHP

Invalid parameters

  • Mahesh1
  • cha2ri
  • PHP5.0.2

validation for alphadash characters

Use: It validates only Alphabets and dashes (under score, dash) i.e small , capital letters,_,-. Input parameter must be trimmed ,it won’t allow spaces also.

Regular Expression

/^([a-zA-Z_-])+$/i

Regular Expression has case insensitive modifier.

PHP function

   /**
     * Matches alpha and dashes like -,_
     * @param   string  
     * @return  boolean
     */
    function is_alphadash($val)
    {
        return (bool)preg_match("/^([A-Za-z_-])+$/i", $val);   }

Valid parameters

  • Mahesh
  • chari_
  • PHP_OOPS

Invalid parameters

  • Mahesh1
  • cha2ri
  • PHP5.0.2
  • $_POST

validate alpha numeric characters

Use: It validates only Alphabets and dashes (under score, dash) i.e small , capital letters,_,-. Input parameter must be trimmed ,it won’t allow spaces also.

alpha numeric characters regular Expression

/^([a-zA-Z0-9])+$/i

Regular Expression has case insensitive modifier.

PHP function

  /**
     * Matches alpha and numbers only
     * @param   string   
     * @return  boolean
     */
    function is_alphanumeric($val)
    {
        return (bool)preg_match("/^([a-zA-Z0-9])+$/i", $val);   }

Valid parameters

  • Mahesh
  • chari
  • PHP OOPS

Invalid parameters

  • PHP5.0.2
  • $_POST

validation for ascii input from a file

Use: It is very important to work with multi language application , we must validate for utf-8, ascii characters.

ascii string format validate Regular Expression

  /[^\x00-\x7F]/i

PHP function

  /**
  * is given string is ascii format?
  * @param   string        
  * @return  boolean
  */   function is_ascii($val)
  {
  return !preg_match('/[^\x00-\x7F]/i', $val);
  }

Valid parameter

We can’t display file specific characters here . just test with note pad text.

Invalid parameter

We can’t display file specific characters here . just test with note pad text.

base64 string Validation

Use: Generelly we encrypt the URL parameters with base64_encode and base64_decode from end users,while validating with sessions,passing secrate data. Then we must check that parameter string for valid base64 encoding.

base64 string Regular Expression

  /[^a-zA-Z0-9\/\+=]/

PHP function

  /**
  * Matches base64 enoding string
  * @param   string   
  * @return  boolean
  */
  function is_base64($val)
  {
  return (bool)!preg_match('/[^a-zA-Z0-9\/\+=]/', $val);   }

Valid parameter

base64 encoded string

Invalid parameter

non base64 encoded string

Validation for boolean or Bool type

Use: Generelly we use so many type values for number (1,0), strings (‘yes’,’no’),(’1′,’0′),bool (true,false)

PHP function

Custom function that validates informal and formal type of boolean.

  /**
  * is given field is boolean value or not
  * @param   string   
  * @return  boolean
  */
  function is_boolean($val)
  {
  $booleans = array(1, 0, '1', '0', true, false, true, false);
  $literals = array('true', 'false', 'yes', 'no');
  foreach ($booleans as $bool) {
  if ($val === $bool)
  return true;
  }   return in_array(strtolower($val), $literals);
  }

PHP core function

is_bool() can be used

Valid parameter

1,0,’yes’,’no’,true,false

Invalid parameter

any different paramenter from the above.

Validate credit card number

Use: E-Commerce applications uses,for user credit card validation.

credit card validation Regular Expression

/^((4\d{3})|(5[1-5]\d{2})|(6011)|(7\d{3}))-?\d{4}-?\d{4}-?\d{4}|3[4,7]\d{13}$/

credit card validation php function

  /**
  * Valid Credit Card
  * @param   string   
  * @return  boolean
  */
  function is_creditcard($val)
  {
  return (bool)preg_match("/^((4\d{3})|(5[1-5]\d{2})|(6011)|(7\d{3}))-?\d{4}-?\d{4}-?\d{4}|3[4,7]\d{13}$/",
  $val);   }

Validation for date any format

Use: While validating time event dependent applications like organising,appointment..etc application we use date validation.

PHP function

  /**
  * Check if given string matches any format date
  * @param   string   
  * @return  boolean
  */
  function is_date($val)
  {
  return (strtotime($val) !== false);   }

Validation for dateDe [d.m.y]

Use: While validating time event dependent applications like organising,appointment..etc application we use date validation.

date de validation Regular Expression

/^\d\d?\.\d\d?\.\d\d\d?\d?$/

PHP function

  /**
  * Checks given value matches date de
  * @param   string         
  * @return  boolean
  */   function is_dateDE($date)
  {
  return (bool)preg_match("/^\d\d?\.\d\d?\.\d\d\d?\d?$/", $date);
  }

Validation for dateISO

Use: While validating time event dependent applications like organising,appointment..etc application we use date validation.

iso date Regular Expression

/^\d{4}[\/-]\d{1,2}[\/-]\d{1,2}$/

PHP validate date iso function

  /**
  * Checks given value matches us citizen social security number
  * @param   string         
  * @return  boolean
  */
  function is_dateISO($date)
  {
  return (bool)preg_match("/^\d{4}[\/-]\d{1,2}[\/-]\d{1,2}$/", $date);
  }

Validation for decimal

Use: Validation while processing ecommerce form for money values.

decimal validation Regular Expression

/^\d+(\.\d{1,6})?$/

PHP function

  /**
  * check decimal with . is optional and after decimal places up to 6th precision
  * @param   string   
  * @return  boolean
  */
  function is_decimal($val)
  {
  return (bool)preg_match("/^\d+(\.\d{1,6})?$/'", $val);   }

Validation for email address

Use: validation on user registration ,contact forms.

email address validation Regular Expression

/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/ix

PHP email address validation function

  /**
  * valid email     
  * @param   string   
  * @return  boolean
  */
  function is_email($val)
  {
  return (bool)(preg_match("/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/ix",
  $val));   }

validate email domain exists

Use: validation on user registration ,contact forms. Before testing this function check it is valid email.

email Regular Expression

/^[^@]++@/

PHP function

  /**
  * Checks that a field is exactly the right length.
  * @param   string   value
  * @link  http://php.net/checkdnsrr  not added to Windows until PHP 5.3.0
  * @return  boolean
  */
  function is_emaildomain($email)
  {
  return (bool)checkdnsrr(preg_replace('/^[^@]++@/', '', $email), 'MX');   }

Validation for empty input for all type

Use: validate the input parameter that is string ,boolean,array ,object, null .etc types also for empty

PHP validate function

  /**
  * check if field empty string ,orject,array
  * @param   string   
  * @return  boolean
  */
  function is_empty($val)
  {
  return in_array($val, array(null, false, '', array(),(object)array()), true);   }

Validation for enum

Use: we need to check a value for fixed number of specified values only, takes a input value and compares the given array, it is alias of in_array PHP function

PHP function

  /**
  * check given string againest given array values
  * @param   string   
  * @return  boolean
  */
  function is_enum($val, $arr)
  {
  return in_array($val, $arr);   }

Validation for variable exists

Use: check if a array key element exists.

PHP function

  /**
  * check given array key element exists?
  * @param   string   
  * @return  boolean
  */   function is_exists($val, $arr)
  {
  return isset($arr[$val]);   }

Validate hexa decimal color

Use: validate the given value for hexa decimal color format

hexa decimal color Regular Expression

/^#?+[0-9a-f]{3}(?:[0-9a-f]{3})?$/i

PHP function

  /**
  * Valid hexadecimal color ,that may have #,
  * @param   string   
  * @return  boolean
  */
  function is_hexcolor($color)
  {
  return (bool)preg_match('/^#?+[0-9a-f]{3}(?:[0-9a-f]{3})?$/i', $color);   }

Validate html tags

Use: It is best practice to validate our forms textarea elements data againest HTML content ,before we displaying HTML with Mysql data. If we don’t validate this will override our Web page template layout.

HTML tag Regular Expression

/<(.*)>.*<$1>/

PHP HTML tag validation function

  /**
  * given sting has html tags?
  * @param   string   
  * @return  boolean
  */
  function is_htmlsafe($val)
  {
  return (bool)(!preg_match("/<(.*)>.*
  <$1>
  /", $val));   }

Validation for integer

Use: validate integer

validate input for integer php function

  /**
  *Matches exactly number
  * @param   string   
  * @return  boolean
  */
  function is_integer($val)
  {
  return is_int($val);   }

Validate ip address

Use: It is best practice to validate user remote address with PHP , in some times user may comes as anonymus i.e Proxy enabled . it is best used in IP bound applications like polling, affiliate marketing applications..

ip address validation Regular Expression

/<(.*)>.*<$1>/

ip address validate php function

  /**
  * Valid IP address
  * @param   string   
  * @return  boolean
  */
  function is_ipaddress($val)
  {
  return (bool)preg_match("/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/",
  $val);   }



Download the code

http://www.maheshchari.com/60-validation-functions-with-php/

Leave a comment