简体   繁体   中英

Angular custom validation for HTML file browse using Form Builder

I'm using reactive form validation and need to validate a file upload control. At the moment I'm using a change directive to handle it's validation.

<label class="btn btn-primary btn-file">
   Browse <input type="file" (change)="fileChanged($event)" style="display:none;">
</label>

And build the form then subscribe to it's changes:

this.myForm = this.formBuilder.group({
            'title': [
                this.chart.title,
                [Validators.required]
            ],
            'description': [
                this.chart.description,
                [Validators.required]
            ]
        });


this.myForm.valueChanges.subscribe(data => this.onValueChanged(data));

Can I put the upload/file browse into the form builder and use custom validation for it from there?

First create a control in your form, but don't assign it to the input via formControlName . Instead you want to keep using the (change) event but then in the change function you want to add the file value to the control. You also want to write a custom validator that will check whatever you need to check with the file. Here's how it would look (isch):

// Add title & description here too
this.myForm = this.fb.group({file: [null, [Validators.required, FileValidator]]});

onValueChanged(file): void {
  this.myForm.get('file').setValue(file);
}

file.validator.ts :

export const FileValidator = (): ValidatorFn => {

  return (control: FormControl): {[key: string]: boolean} => {

    // Do whatever checking you need here
    const valid: boolean = true;

    return valid ? null : {
      file: true
    };
  };
};

The validation will check whatever value that is in the file control so you won't have to manually validate it in a separate function.

I hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM