2

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>

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

4 Comments

Mate, your a legend i've been stuck on that for a while
No problem, Mr Code :)
Btw, the way I debugged this was to display the actual json in the HTML. <pre>{{form.controls.jsonField.errors | json}}</pre>
Ah that's very clever I like that thanks a'lot for taking the time I really appreciate it

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.