Search code examples
jsonangulartypescriptvalidationangular-forms

How to display custom validation error message


For my form it has just one input and that's a text area, where the user enters in JSON Code and if the Text is not Valid JSON it should display an error message but for some reason it wont work.

Here's my custom validator:

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;
};

Here is the .ts File

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 Finally the HTML File

<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>

Solution

  • Your validation error name is jsonInvalid, not jsonValidator.

    The name is defined by the return statement in your validator function.

    return { jsonInvalid: true };
    

    You should use this in your HTML:

    <div *ngIf="form.controls.jsonField.hasError('jsonInvalid')">
      {{errorMsg}} 
    </div>
    

    DEMO: https://stackblitz.com/edit/angular-h89jju