1
votes

I have a form with two fields...one is a group of 3 checkboxes (out of which one must be selected) and the other is input type as file.(which must be selected). I am using reactive form custom validators for them and only after providing poper values to the form, I have to enable the submit button. But the validators don't seem to be working.

HTML page :

<input type="file"  id="selectFile" #selectFile accept=".zip" formControlName ="fileUpload" name="file" class="form-control"  class="btn" value="file" required />
<span *ngFor="let tool of toolTypeList">
  <label class="checkbox-inline col-md-2 " style = "text-align: left;padding-left:35px"> 
    <input type="checkbox"  formControlName ="selectTool"
      name="{{tool.toolType}}" 
      value="{{tool.toolType}}"
      (change)="change($event, tool)">
      {{tool.toolType}}
  </label>
</span>

Component :

this.rForm = fb.group({
  'selectTool': new FormControl('', [
    Validators.required,
    this.validateTools
  ]),
  ' fileUpload': new FormControl('', [
    Validators.required,
    this.noFilePresent
  ]),
});

Validators:

noFilePresent(): Boolean {
  if (this.fileuploaded.size <= 0) {
    return true;
  }
  return false;
}

validateTools(c: AbstractControl) {
  console.log('here in custom validator : ' + c.value);
  let response: any = null;
  if (c.value == null) {
    response = this.selectedTools.length > 0 ? null : {
      validateTools: {
        valid: false
      }
    };
  }

I assume for fileUpload field, the validator created is wrong in its structure as no formcontrol object is passed as parameter. But with presumably correct structure of checkbox (selectTool) validator, It's not working. Please help me find my mistake. Thanks in advance.

1
Put the validators outside of the class.rrd
@rrd you mean I should define the validators outside the component where I am calling them?ABHISHEK SRIVASTAVA
Yes. Usually I include them in the same file, just outside the class. You won't refer to them with 'this'. If you want to make them reusable, you would have them in separate files and import them ofc.rrd

1 Answers

1
votes

I created my custom validators like this. Can be in your class if you only need them there and refered to just like you did.

private noFilePresent(): ValidatorFn {
    return (control: AbstractControl): { [key: string]: any } => {
        if(control.value == null || control.value.length == 0) {
            return {'uploadInvalid': {value: control.value}};
        }
        return null;
    }
}

I think the value which is control.value here can be about any value. You can then check if there is an error using a getter

 get upload() { return this.rForm.get('fileUpload'); }

and somewhere else

 if(this.upload.errors.uploadInvalid) {
     // do stuff or return error message or something
 }