0

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->setErrorByName('document', $this->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?

2
  • Is there a reason you can't just change the "Allowed file extensions" setting on the field config page?
    – Clive
    Commented Nov 26, 2018 at 14:12
  • 1
    Yes, is this a "field" or is this a vanilla Form API field in a custom form?
    – Kevin
    Commented Nov 26, 2018 at 14:29

1 Answer 1

1

That's basic logic. Change your ORs to ANDs.

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->setErrorByName('document', $this->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) {
  // ...
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.