Tengo una clase MyValidators con el siguiente método:
import { AbstractControl } from '@angular/forms';
export class MyValidators{
static cleanUnnecessaryWhiteSpaces(control: AbstractControl){
const value = control.value;
const cleanString = value.replace(/\s{2,}/g, ' ').trim();
return cleanString;
}
Despues implemento este validator personalizado cleanUnnecessaryWhiteSpaces
en mi formulario
import { MyValidators } from '../../../utils/myValidators';
export class BookFormComponent implements OnInit {
cad: string;
form: FormGroup;
book = {} as Book; // declaro el objeto Book vacio
// obteniendo año actual
today = new Date();
year = this.today.getFullYear();
constructor(
public bookService: BookService,
private toastr: ToastrService,
private formBuilder: FormBuilder
) {
// function buildForm
this.buildForm();
}
ngOnInit(): void {
}
buildForm() {
this.form = this.formBuilder.group({
name: ['', [Validators.required, Validators.maxLength(50), MyValidators.cleanUnnecessaryWhiteSpaces]],
year: ['', [Validators.required, Validators.max(this.year)]],
author: ['', [Validators.required]],
category: ['', [Validators.required]],
editorial: ['', [Validators.required]],
description: ['', [Validators.required, Validators.maxLength(300)]],
quantity: ['', [Validators.required]],
price: [0, [Validators.required]],
image: [''],
state: [true]
});
}
}
pero por consola angular muestra este error:
core.js:4197 ERROR TypeError: Cannot read property 'replace' of undefined at cleanUnnecessaryWhiteSpaces (myValidators.ts:13) at forms.js:1169 at Array.map () at executeValidators (forms.js:1169) at forms.js:1123 at forms.js:1169 at Array.map () at executeValidators (forms.js:1169) at FormControl.validator (forms.js:112