Tips for showcasing unique validation error messages

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>

Answer №1

Your error validation code is jsonInvalid, not jsonValidator.

The specific name is determined by the return statement within your validator function.

return { jsonInvalid: true };

To implement this in your HTML, you should use:

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

Try it out here: https://stackblitz.com/edit/angular-h89jju

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error in AWS Cloud Development Kit: Cannot access properties of undefined while trying to read 'Parameters'

I am currently utilizing aws cdk 2.132.1 to implement a basic Lambda application. Within my project, there is one stack named AllStack.ts which acts as the parent stack for all other stacks (DynamoDB, SNS, SQS, StepFunction, etc.), here is an overview: im ...

Aggregate the values in an array and organize them into an object based on their frequency

I have an array of information structured like this: 0: { first: "sea", second: "deniz", languageId: "English-Turkish"} 1: { first: "play", second: "oynamak", languageId: "English-Turkish&qu ...

Using JavaScript to send formatted text through POST requests in a Rails application

Within APP A, I have the following formatted text: A beautiful painting because I created it because an artist endorsed it because my cat loves it I can access this formatted text in index.html.erb through product.body_html, which I then load into a Ja ...

Issues with Imported Routes Not Functioning as Expected

I am currently working on implementing routing in my Angular 2 project. All the components are functioning properly, but I encounter an error when I include 'appRoutes' in the imports section of app.module.ts. An unexpected TypeError occurs: C ...

Error: Attempting to access the property 'cinemaName' of an undefined object

I am brand new to using angular2 and higher. My form definition with an input field of type text looks like this: <form class="form-horizontal" name="form" role="form"> <div class="form-group"> <label class="col-md-3 co ...

Guide on transferring the token and user information from the backend to the front-end

Here is the code from my userservice.ts file export class UserService { BASE_URL = "http://localhost:8082"; constructor(private httpClient:HttpClient) {} public login(loginData:any){ return this.httpClient.post(this.BASE_URL+"/au ...

How to use D3 to add arrow directions to an SVG path

Within my svg path lies the representation of a shuttle track used in manufacturing processes. Every shuttle on this track moves in a distinct direction, and I wanted the svg path to visually indicate these directions for easy reference. Initially, I tried ...

Unable to modify the text value of the input field

I am currently learning how to code in React, so please forgive me if my question seems basic. I am attempting to change the text of an Input element based on the value of the filtered variable, like this: const contactContext = useContext(ContactContext); ...

Error on the main thread in NativeScript Angular for Android has not been caught

As a beginner in the field of mobile development, I am currently exploring NativeScript and encountering an error in my Android application. https://i.stack.imgur.com/BxLqb.png You can view my package.json here ...

Differentiating elements from two array objects in typescript: a guide

I am facing an issue in extracting the different elements from two array objects. Here is my example: array1 = [{id: 1, a: "a", b: "b"}, {id: 2, c: "c", d: "d"}, {id: 3, e: "e", f: "f"}]; array2 = ...

LightWeightChart: How do I incorporate a chart that resembles this style?

Is it possible to create a chart using lightweight-chart that includes two graphs sharing the same x-axis but with different values on the y-axis? Essentially, I want to have two panes in a single chart. Does anyone have suggestions or tips on how this c ...

How to Delete Multiple Rows from an Angular 4 Table

I have successfully figured out how to remove a single row from a table using splice method. Now, I am looking to extend this functionality to remove multiple rows at once. html <tr *ngFor="let member of members; let i = index;"> <td> ...

Place the id in the queue just like you would when adding to your cart

After successfully creating model schemas for users and products and implementing simple CRUD operations, my next project involves creating a model schema for orders. In this new model schema, I plan to push the userId and projectId into an array in a spec ...

The Wialon Wireless Location Protocol (WLP) format

In the past, I developed a view in our previous system to expose the necessary data for creating new vehicles in Wialon. Recently, I have created a small c# application to convert each vehicle into a WLP file for easy importing. A WLP file is essentially a ...

Tips for stopping </p> from breaking the line

<p>Available: </p><p style={{color:'green'}}>{props.active_count}</p><p>Unavailable: </p><p style={{color:'red'}}>{props.inactive_count}</p> https://i.sstatic.net/NQo5e.png I want the ou ...

Volta alert: Temporary directory creation failed

Recently, I attempted to globally download and install TypeScript using the npm install -g typescript command in my terminal. Unfortunately, an error occurred: Volta error: Could not create temporary directory in /Users/username/.volta/tmp/image/packages ...

Is it possible for the Observable call in Angular 4 to function similarly to jQuery's synchronous AJAX method?

As I have a business logic function that needs to use HttpGet and I must wait for the result before continuing, jQuery's ajax can handle this easily. But I am curious if Observables have a similar feature? I was hoping for the result to be: John An ...

Monaco utilized for Angular web-based code editing platform

We recently created an online code editor in our project using the Monaco editor. Our next goal is to integrate an Angular editor into this platform. To achieve this, we require NPM support to install dependencies directly from the editor. If anyone has ...

`The flaw in filtering logic - an analysis`

Looking to find matching records within two Lists. We have a List called allAnimals with attributes like animalId, and another List named domesticAnimals also containing animalId. The goal is to compare the two lists and create a new list where the anima ...

Reducing SCSS import path in Angular 7

Creating a component that is deeply nested raises the issue of importing shared .scss files with long paths: @import '../../../app.shared.scss'; This hassle doesn't exist when it comes to .ts files, thanks to the configuration in tsconfig. ...