How to validate allowed file types in custom module I want to validate a field with accepted file type as PDF, XLS, JPEG, JPG, GIF, ZIP, RAR and PNG.

I'm getting file types as PDF, XLS etc. here is part of my code.

if ($fi_name!='') {

  if ($p_filefilename[1] != 'pdf'
    ||$p_filefilename[1] != 'xls'
    ||$p_filefilename[1] != 'jpeg'
    ||$p_filefilename[1] != 'jpg'
    ||$p_filefilename[1] != 'zip'
    ||$p_filefilename[1] != 'rar'
    ||$p_filefilename[1] != 'png') {

    $form_state-&gt;setErrorByName('document', $this-&gt;t('Please upload document  in pdf, xls, jpeg, jpg, gif, zip, rar and png file.'));
  }
}


Even when I'm uploading PDF files it's going to error part and showing my message as "Please upload document  in pdf, xls, jpeg, jpg, gif, zip, rar and png file."

What am I doing wrong?
That's basic logic. Change your ORs to ANDs.

if ($p_filefilename[1] != 'pdf'
  &amp;&amp; $p_filefilename[1] != 'xls'
  &amp;&amp; $p_filefilename[1] != 'jpeg'
  &amp;&amp; $p_filefilename[1] != 'jpg'
  &amp;&amp; $p_filefilename[1] != 'zip'
  &amp;&amp; $p_filefilename[1] != 'rar'
  &amp;&amp; $p_filefilename[1] != 'png') {

  $form_state-&gt;setErrorByName('document', $this-&gt;t('Please upload document  in pdf, xls, jpeg, jpg, gif, zip, rar and png file.'));
}


Anyway, you should use in_array() for that check. For example:

$allowed_types = array('pdf','xls','jpeg','jpg', 'zip','rar','png');
if (!in_array($p_filefilename[1], $allowed_types) {
  // ...
}