I have a MyValidators class with the following method:
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;
}
Then I implement this custom validator cleanUnnecessaryWhiteSpaces
in my form
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]
});
}
}
but by angular console it shows this 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
What you are receiving is not a
formControl
, but the value of the control:Validations do not change the data you receive. Angular expects an object when validation is wrong. This object must contain the data that you want to display by not passing the defined rules. If the validation is correct, a
null
. Your current logic will always fail with text, and will succeed with nothing written.You can refine the data when you send your form. Doing it the way you propose will lead to a difficulty in your code that personally, I do not recommend you address.