Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

143
Views
Angular File upload validator failed

I tried to build validator for uploaded file in front end using angular. My validator is simple. I put function onFileChange(event) on file input form to get properties from file that would be uploaded. Then I tried to filter it. Just png, jpg, jpeg and pdf file can be uploaded. But it did not work as expected. When I upload png file, it shows alert popup. This is my onFileChange(event on component.ts

onFileChange(event:any){
    if(event.target.files.length > 0){
      this.selectedFile = event.target.files[0]
      if(this.selectedFile.type != "image/png" || this.selectedFile.type != "image/jpg" || this.selectedFile.type != "image/jpeg" || this.selectedFile.type != "application/pdf" ){
        alert("File type must be png,jpg,jpeg and pdf")
      }
      console.log(this.selectedFile)
    }
  }

And this is my html file

          <div class="mb-3">
            <label for="formFile" class="form-label">Pilih File</label>
            <input class="form-control" type="file" id="file" (change)="onFileChange($event)">
          </div>

Hope someone can help me. Thank you

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

The problem is that you are using || instead of &&

onFileChange(event:any){
  if(event.target.files.length > 0){
    this.selectedFile = event.target.files?[0];
    if(this.selectedFile){
      // no file selected
      return;
    }
    if(this.selectedFile.type !== "image/png" &&
    this.selectedFile.type !== "image/jpg" &&
    this.selectedFile.type !== "image/jpeg" &&
    this.selectedFile.type !== "application/pdf" ){
      alert("File type must be png, jpg, jpeg or pdf")
    }
  }
}

our you could do the opposite:

if(this.selectedFile.type === "image/png" ||
    this.selectedFile.type === "image/jpg" ||
    this.selectedFile.type === "image/jpeg" ||
    this.selectedFile.type === "application/pdf" ){
    // the file is OK
} else {
    alert("File type must be png, jpg, jpeg or pdf")
}
    ```
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!