My form includes a text area for the user to input JSON Code. If the entered text is not valid JSON, an error message should be displayed but unfortunately, it's not working as expected.
Below is my custom validator code:
import { AbstractControl, ValidationErrors, ValidatorFn } from '@angular/forms';
export function jsonValidator(control: AbstractControl): ValidationErrors | null {
try {
JSON.parse(control.value);
} catch (e) {
console.log("Not Valid JSON");
return { jsonInvalid: true };
}
return null;
};
This is the .ts file where the validator is implemented:
import { Component, OnInit } from '@angular/core';
import { FormBuilder, Validators, FormGroup } from '@angular/forms';
import { jsonValidator } from 'src/app/Validators/jsonValid';
@Component({
selector: 'app-email-body-editor',
templateUrl: './email-body-editor.component.html',
styleUrls: ['./email-body-editor.component.scss']
})
export class EmailBodyEditorComponent implements OnInit {
errorMsg : string = "Not VALID JSON";
form = this.fb.group({
jsonField: [null, [Validators.required , jsonValidator]]
});
constructor(private fb: FormBuilder) {
}
submit(): void {
console.log(this.form);
}
ngOnInit(): void {
}
}
And now, here's the HTML file where the form is rendered:
<form [formGroup]="form" (submit)="submit()">
<mat-form-field appearance="fill">
<mat-label>Textarea</mat-label>
<textarea matInput
formControlName="jsonField"
cols="1000"
placeholder="my custom json here"
cdkTextareaAutosize
cdkAutosizeMinRows="10"
cdkAutosizeMaxRows="50">
</textarea>
</mat-form-field>
<br>
<div *ngIf="form.controls.jsonField.hasError('jsonValidator')">
{{errorMsg}}
</div>
</form>