Verification of symmetrical file formatting

When dealing with three separate file upload inputs, the challenge is to ensure that the uploaded files are not duplicates. Additionally, if the user selects image format files (such as png, jpg, jpeg), they must select all three inputs in image format. On the other hand, if a PDF file is chosen, only PDF format files should be uploaded.

Therefore, the user can upload either all images (png, jpg, jpeg) or PDFs, but not a combination of both.

The approach involves using the ".replace(/^.*\./, "").toLowerCase();" regex to extract file extensions and applying various if-else conditions for validation.

//html

<ng-container>
    <span>
        <label class="label1">
            <div>
                <span>
                    <img class="image1 " src="assets/images/upload.png " alt="img " width="30 " height="30 " />
                </span>
                <span style="cursor:pointer;">{{salary1}}</span>
                <span>
                    <input type="file" (change)="selectFileS1($event) " accept=".jpg, .jpeg, .png, .pdf ">
                </span>
            </div>
        </label>
    </span>
    <span>
        <label class="label1">
            <img class="image2 " src="assets/images/upload.png " alt="img " width="30 " height="30 " />

            <span style="cursor:pointer;">{{salary2}}</span>
            <input type="file" (change)="selectFileS2($event) " accept=".jpg, .jpeg, .png, .pdf ">
        </label>
    </span>
    <span>
        <label class="label1 ">
            <img class="image3 " src="assets/images/upload.png " alt="img " width="30 " height="30 " />
            <span style="cursor:pointer;">{{salary3}}</span>
            <input type="file" (change)="selectFileS3($event) " accept=".jpg, .jpeg, .png, .pdf ">
        </label>
    </span>
    <br>
</ng-container>

//ts

selectMonth1 = [];
selectMonth2 = [];
selectMonth3 = [];
salary1  = 'Month / Combined';
salary2  = 'Month2';
salary3  = 'Month3';


selectFileS1(event) {
    this.selectMonth1 = Array.from(event.target.files);
    console.log(this.selectMonth1);

   if(!this.validationMethod()) {
        this.salary1 = this.selectMonth1[0].name;
    }

}

selectFileS2(event) {
    this.selectMonth2 = Array.from(event.target.files);
    if(!this.validationMethod()) {
        this.salary2 = this.selectMonth2[0].name;
    }
}

selectFileS3(event) {
    this.selectMonth3 = Array.from(event.target.files);
    if(!this.validationMethod()) {
        this.salary3 = this.selectMonth3[0].name;
    }
}


validationMethod() {
    // Validation logic goes here
}

Answer №1

Keep it simple.

<input type="file" (change)="selectFile($event)" [accept]="allowedExtensions">
export class MyComponent {
  allowedExtensions = 'image/*, application/pdf';

  extensions = {
    images: ['jpeg', 'jpg', 'png'], //etc
  };

  constructor(...) {}

  selectFile(event: Event) {
    const input = event.target as HTMLInputElement;
    const FL = input.files;
    const file = FL[0];
    this.setExtensions(file.name.split('.').slice(-1));
    // ... Your optimized logic here
  }

  setExtensions(extension: string) {
    if (this.extensions.images.includes(extension)) { this.allowedExtensions = this.extensions.map(ext => `.${ext}`).join(','); }
    else if (extension === 'pdf') { this.allowedExtensions = 'application/pdf' }
    else { this.allowedExtensions = 'image/*, application/pdf'; }
  }
}

There is always room for improvement, but this outlines the basic steps to follow.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Transforming button properties into a JSON format

I am currently in the process of developing a web application using node.js and mongodb. Within my app, there is a table that dynamically populates data from the database using a loop. I encountered an issue with a delete function that I implemented base ...

The project is not being recognized by 'webpack' when running within it

Every time I attempt to execute 'webpack' in my project, the command line shows me this error message: 'webpack' is not recognized as an internal or external command, operable program or batch file. I have installed webpack using th ...

Issue occurred when trying to load controllers during the migration process from AngularJS1 to Angular6

Currently, I am in the process of upgrading AngularJS1 components to Angular6. My strategy involves creating wrappers for all existing AngularJS1 components by extending "UpgradeComponent" and storing them under the folder "directive-wrappers". However, wh ...

Retrieve information using AJAX via POST method

I find myself in a bit of a pickle at the moment. I've been researching for hours, and I still can't seem to figure out this seemingly basic issue. It would be greatly appreciated if someone could offer me some quick advice. So here's my dil ...

What is the recommended sequence for adding AngularJS to the index page?

I am new to AngularJS and currently working on a project where I need to include multiple JavaScript files in my index.html page. After doing some research, I came across a post on Stack Overflow that mentioned the importance of including the angular.js fi ...

Next.js encountered an API resolution issue while uploading a file, resulting in no response being

Even though my code is functioning properly, a warning appears in the console: The API call was resolved without sending any response for /api/image-upload This particular endpoint is responsible for uploading an image to Digital Ocean's object sto ...

Searching through text in Node JS using Mongoose for Full-Text queries

I am facing an issue while attempting to perform a full-text search on an array of strings using Mongoose. The error message I receive is as follows: { [MongoError: text index required for $text query] name: 'MongoError', message: 'text ...

Interactive image map with hover effects and external image swapping placed beyond the container

I've encountered a problem with a responsive image map and rollovers. Using Matt Stow's responsive image jQuery plugin ensures that coordinates are responsive, and clicking on an area brings up Lightview as expected. However, the issue arises whe ...

Preserve the original position of the inner <div> when animating the container <div> using JQuery

I am currently working on a small website and encountering some challenges with jQuery animation. My issue involves placing a single character text inside a circle and wanting it to grow when the user hovers over it, while keeping the inner text in its ori ...

Increase or decrease the quantity of items by cloning with Jquery and dynamically changing the ID

Currently, I am working on a jQuery clone project where I need to dynamically add and delete rows. Despite searching extensively on Stack Overflow and Google, I only have a basic understanding of how jQuery clone works. Any suggestions would be greatly ap ...

Having trouble getting the Angular2 boilerplate to start with npm?

Just starting out with Angular2 and attempting to set up the environment using the boilerplate code found at https://github.com/mschwarzmueller/angular-2-beta-boilerplate. After successfully installing my dependencies with npm install, I encountered some ...

There was an issue locating a declaration file for the module 'clarifai'

https://i.stack.imgur.com/PgfqO.jpg I recently encountered a problem after installing the Clarifai API for a face recognition project. Despite my efforts, I have been unable to find a solution. When I hover over "import clarifai," I receive the message: ...

Exploring ways to utilize Next.js (React) for formatting date and time with either Moment.js or alternate

When deciding on the best method for handling date formats in my next front-end app, should I use Moment.js or JavaScript functions? The data is sourced from the backend as the date type, and I want it to be displayed in a user-friendly format while consid ...

Using Selenium Webdriver to set a cookie with a Chrome extension

I have been experimenting with a Chrome extension in order to set a cookie when I use a Selenium Webdriver instance to open a page. Despite trying various methods suggested on different Stack Overflow posts, none of them seem to work as the cookie does not ...

When logging off from an Angular2 application, the OIDC-client does not properly clear the cookies for the MVC application

I currently have an authorization server that is being used by both my Angular2 app and MVC webapp. In my Angular2 app, I've implemented authorization using the oidc-client JavaScript package. Everything works well except for the logout functionality ...

Encountering an issue with Auth0 and Angular2: "The supplied parameters do not match any signature of call target."

I'm currently in the process of integrating Auth0 with my Angular2 application using angular2-cli. I've added a new service called auth, but when I try running npm start, I encounter an error stating: src/app/auth.service.ts (21,5): Supplied para ...

Harnessing the Power of FormControlName and Labels in Angular 6

In my project using Angular 6 and reactive forms, I have a grid with a Detail button that opens a modal window displaying student information. However, when implementing the HTML for the dialog box as shown below, I encountered an error message stating: No ...

How can VueJs effectively update the data fetched using the created function?

When working with the Promise Object, I prefer to utilize the "then" and "catch" functions instead of asynchronous functions for handling responses in a simpler way. This allows me to avoid using await and conditional if-else statements to check the stat ...

What is the most efficient method for delivering a script along with the initial index.html file?

Currently, I have my JavaScript code inline in the index.html file, but I want to move it to a separate file. <script> ... my code </script> After doing some research, I found that there are server side includes which seem outdated. There are ...

"Troubleshooting the issue of Delete Requests failing to persist in Node.js

Whenever I send a delete request to my node.js server, it can only delete one item from my JSON file until the server restarts. If I attempt to make a second delete request, it successfully deletes the item but also reverts the deletion of the last item. ...