DEV Community

Ajay Ojha
Ajay Ojha

Posted on

File validation in Angular Reactive Form

File validation is a little bit clumsy task to do in the angular reactive forms. Here we discuss how we can optimize the code and achieve our goal to validate the file before passing to the server.

Let's understand the functional requirement:

  • The form should accept only jpeg and gif files and the files resolution is around 100 by 100 pixel.
  • The File object should be stored as a value in the FormControl.

Let's dive into the code to fulfill the requirement. We use extension and file validator of RxwebValidator.

As RxwebValidator is not the part of Angular framework, So we have to install the @rxweb/reactive-form-validators package to avail the services of RxwebValidator.

npm install @rxweb/reactive-form-validators

Now, we have to register the 'RxReactiveFormsModule' in the root module.

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule,ReactiveFormsModule } from '@angular/forms';
import { AppComponent } from './app.component';

import {  RxReactiveFormsModule } from "@rxweb/reactive-form-validators"
@NgModule({
  imports:      [ BrowserModule, FormsModule,ReactiveFormsModule,RxReactiveFormsModule ],
  declarations: [ AppComponent],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

Let's create a profilePhoto FormControl and set the image and extension validator on that.

        this.userInfoFormGroup = this.formBuilder.group({
            profilePhoto:['', [ 
                                 RxwebValidators.image({maxHeight:100,maxWidth:100 }),
                                 RxwebValidators.extension({extensions:["jpeg","gif"]})
                                 ]       
                            ], 
        });

As per the above code we have used image validator to restrict user to upload the image upto 100 pixel of height and width and the allowed extensions are "jpeg" and "gif".

Here, is the complete code of the component:

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder } from "@angular/forms"
import { RxwebValidators } from '@rxweb/reactive-form-validators';

@Component({
    selector: 'app-image-add-validator',
    templateUrl: './image-add.component.html'
})
export class ImageAddValidatorComponent implements OnInit {
    userInfoFormGroup: FormGroup

    constructor(
        private formBuilder: FormBuilder )
    { }

    ngOnInit() {
        this.userInfoFormGroup = this.formBuilder.group({
            profilePhoto:['', [ 
                                 RxwebValidators.image({maxHeight:100,maxWidth:100 }),
                                 RxwebValidators.extension({extensions:["jpeg","gif"]})
                                 ]       
                            ], 
        });
    }
}

As we also want to file object should be stored as a value in the FormControl.
For that, we have to write the attribute([writeFile]="true") on the input file control.
See the HTML code below:

<div>
  <form  [formGroup]="userInfoFormGroup">
    <div class="form-group">
      <label>Profile Photo</label>
      <input [writeFile]="true" type="file" formControlName="profilePhoto" class="form-control"  />
    </div>

    <button [disabled]="!userInfoFormGroup.valid" class="btn btn-primary">Submit</button>
  </form>
</div>

All Done!.

Please refer to the stackblitz example.

As we have discussed on the file validation, then one scenario coming into every application which is mentioned below:

How to restrict the user up to certain files?

In this case, you have to use file validator and specify the minimum or/and maximum files.
Here is the code of file validator.

        this.userInfoFormGroup = this.formBuilder.group({
            files:['', RxwebValidators.file({minFiles:2, maxFiles:5 })], 
        });

Please refer the working example of file validator.

If you have any question/suggestion, Please share your comments below.

Top comments (3)

Collapse
 
avinashseth profile image
Avinash Seth

how would you display validation errors ?

Collapse
 
ajayojha profile image
Ajay Ojha

if you have created a FormGroup through FormBuilder then use errors property of respective FormControl or use 'errorMessage' property if you have created a FormGroup through RxFormBuilder.

Collapse
 
piotrpodsiadlo profile image
Piotr Podsiadlo

For some reason after installation IntelliJ informs me that "RxReactiveFormsModule is not an angular module" Anybody had the same problem?