Home > Enterprise >  Custom ValidatorFn use aditional parameters
Custom ValidatorFn use aditional parameters

Time:03-30

Currently I've tried the code bellow but I'm not using the extra data yet.

create-room.component.ts
import { Component, Inject, OnInit } from '@angular/core';
import { AbstractControl, FormBuilder, FormControl, FormGroup, ValidationErrors, ValidatorFn, Validators } from '@angular/forms';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { DialogData } from '../game.component';

@Component({
  selector: 'app-create-room',
  templateUrl: './create-room.component.html',
  styleUrls: ['./create-room.component.scss']
})
export class CreateRoomComponent implements OnInit {
  form!: FormGroup;
  
  constructor(@Inject(MAT_DIALOG_DATA) public data: DialogData, private _formBuilder: FormBuilder, private dialogRef: MatDialogRef<CreateRoomComponent>) { }

  ngOnInit(): void {
    this.form = this._formBuilder.group({
      roomInput: new FormControl("", [Validators.required]),
    }, {validator: roomValidator}); 
  }
  
  ...
}

export const roomValidator: ValidatorFn = (formGroup: AbstractControl ): ValidationErrors | null  => {
  /* Check if the room name already exists */
  var roomName: string = formGroup.get('roomInput')?.value;

  // use data from MAT_DIALOG_DATA INJECT here

  if (true) {
    return { nameWrong: true };
  }

  return null;
}

How can I use the data that the Dialog receives inside the custom ValidatorFn.

Should I pass the this.data as an argument?

CodePudding user response:

change your validator definition to be a function that takes whatever parameters you need, and returns a ValidatorFn:

export const roomValidator = (data: DialogData): ValidatorFn => {
  return (formGroup: AbstractControl ): ValidationErrors | null  => {
    /* Check if the room name already exists */
    var roomName: string = formGroup.get('roomInput')?.value;

    // use data param

    if (true) {
      return { nameWrong: true };
    }

    return null;
  }
}

then use it like so:

  ngOnInit(): void {
    this.form = this._formBuilder.group({
      roomInput: new FormControl("", [Validators.required]),
    }, {validator: roomValidator(this.data)}); 
  }

CodePudding user response:

You have multiple options:

  • Pass the data to the validator as argument
  • Adding NG_VALUE_ACCESSOR and implementing ControlValueAccessor NG_VALUE_ACCESSOR to create a custom formgroup validation
  • Related