A unique directive that showcases both default and custom errors sequentially

In my project, I am facing a challenge where I need to compare the input text with a series of inbuilt errors such as required, minlength, maxlength, and pattern. Additionally, I also need to validate the input against a custom condition using a Custom Validator Directive. However, when using this directive, multiple error messages are displayed simultaneously which is not desired. Despite trying various combinations, I have been unable to display only one error message at a time.

Therefore, I am looking to develop a generic Directive that can achieve the following objectives:
1) Display all inbuilt errors along with our custom errors.
2) Show only one error message at a time.
3) Prioritize inbuilt errors like required and pattern before validating against our custom condition.

HTML Code

<form name="checkForm" #checkForm="ngForm">
    <label>Check Code :<br>
        <input type="text" name="checkFiled" required pattern="^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9]).{8,}"
            [(ngModel)]="checkNgFiled" #checkFiled="ngModel" autocomplete="off"
            [MatchInput]="checkVar">
    </label><br>
        <div *ngIf="(checkFiled.touched || checkFiled.dirty) && checkFiled.invalid"
            class="ErrCls">
            <span *ngIf="checkFiled.errors.required">Input is Empty.</span>
            <span *ngIf="checkFiled.errors.pattern">Code is weak</span>
            <span *ngIf="checkFiled.errors.unMatchError">Input do not match</span><br>
        </div>

    <button [disabled]="!checkForm.valid">Check</button>
</form>

TS Code

import { Directive, Input } from '@angular/core';
import { AbstractControl, Validator, NG_VALIDATORS, ValidationErrors } from '@angular/forms';

@Directive({
    selector: '[MatchInput]',
    providers: [
        { provide: NG_VALIDATORS, useExisting: MatchInputCls, multi: true }
      ]
})
export class MatchInputCls implements Validator
{
    @Input() MatchInput: string;

    validate(inputControl: AbstractControl): ValidationErrors | null
    {

// There is a need to implement a proper condition to prioritize checking for inbuilt errors. If any inbuilt error is present, the code should return null.

        if(!inputControl.errors || (inputControl.errors && 
            Object.keys(inputControl.errors).length == 1 &&
            inputControl.errors.unMatchError ))
        {
            if(inputControl.value != this.MatchInput)
            {
                return { unMatchError: true };
            }
        }
        console.log("OutSide", inputControl.errors)
        return null;
    }
}

Answer №1

Here is an example of how you can create a customValidator:

customValidator(params: any) {
    return (control: AbstractControl) => {
      // Add your logic here
      if (error)
        return { "customError": "An error occurred in the component function: The value is " + params }
      else
      {
          if (control.errors)
          {
              if (control.errors.required)
                  return { "customError": "Required field"}

              if (control.errors.pattern)
                  return { "customError": "Pattern error"}
              ...
          }
      }

      return null;
    }
  }

To display the custom error message, use the following code:

<span *ngIf="checkFiled.errors?.customError">
     {{checkFiled.errors?.customError}}
</span>

NOTE: The errors.required may be true, but it is not being utilized in this example.

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

Retrieving a variable value set within a jQuery function from within an Angular 2 component

In the current project, I am facing a situation where I need to work around and initialize jQuery datetimepicker inside an Angular 2 application (with plans to refactor it later). However, when I assign a datetime value to a variable, I encounter a proble ...

The error message "TypeError: (0 , N.createContext) is not a function" indicates that

I'm currently in the process of developing a cutting-edge application using Next.js 14, TypeScript, and Telegram Open Network. However, I've hit a roadblock while attempting to incorporate the TONConnectUIProvider at the root of my app. Upon run ...

Troubleshooting problem with sorting in Angular 4 material header

Using Angular 4 material for a table has presented me with two issues: 1. When sorting a table, it displays the description of the sorting order in the header. I would like to remove this. https://i.sstatic.net/5bHFO.png It displays "Sorted by ascending o ...

Establishing a Recyclable Testing Rendering Method in redux toolkit version 2

In the era of Redux Toolkit v2, a noticeable change occurred with the absence of the EmptyObject type and the unavailability of the PreloadedState type in the @reduxjs/toolkit package. This has led to a requirement of defining all reducers inside the pre ...

The 'Content-Type' header cannot be defined for HTTP GET requests

I am currently working on setting up my GET requests to include the specific header: Content-Type: application/json Based on information from the documentation, I need to make the following adjustment: To customize these defaults, you can add or remov ...

What could be causing the issue of Vuejs 3.3 defineModel consistently returning undefined?

I am currently working with Nuxt version 3.5.1 and Vuejs version 3.3, however, I am encountering an issue where the defineModel macro always returns undefined. I am unsure why this is happening? <template> <input v-model="count"& ...

What is the best way to execute TypeScript programs on an Android device?

Is there a way to execute TypeScript programs on an Android phone? Are there any offline apps specifically designed for running TypeScript programs on Android devices? ...

Errors related to reducer types in createSlice of Redux Toolkit

As I embark on a new React-Redux project with Typescript, I find myself facing some challenges despite my previous experience. While my knowledge of React and Redux is solid, I am still getting acquainted with Redux toolkit. Transitioning from a typed back ...

Encountering a problem with npm install due to git not being found

I recently updated my package JSON file with new dependencies and attempted to install npm, but encountered errors indicating that git could not be found: npm ERR! path git npm ERR! code ENOENT npm ERR! errno ENOENT npm ERR! syscall spawn git npm ...

Iterate through each item in an object using Angular

I attempted to utilize a forEach loop, but it's indicating that it's undefined for some reason. Here is my code snippet: var array: MoneyDTO[] = prices array.forEach(function (money: MoneyDTO) { if (money.currency == 'QTW& ...

Preventing unauthorized users from accessing routes and child components in Angular 2

Here is the project structure: AppComponent Nav Component LoginComponent Once the user successfully authenticates through the form connected to Firebase, they are directed to the section accessible only by logged-in users. AccountComponent Profile ...

Retrieving information from a .json file using TypeScript

I am facing an issue with my Angular application. I have successfully loaded a .json file into the application, but getting stuck on accessing the data within the file. I previously asked about this problem but realized that I need help in specifically und ...

Guide on Combine Multiple Observables/Subscriptions into a Nest

1. A Puzzle to Solve I am faced with the challenge of implementing a dynamic language change flow for my blog. Here is an overview of how I envision it: The user initiates a language change by clicking a button that triggers an event (Subject). This eve ...

Compiling TypeScript files for Angular 2 with Atom can be quite time-consuming

Currently, I am utilizing Angular 2 RC-6 by referencing the Angular2 Documentation. However, I have encountered an issue with Atom being too slow to compile my '.ts' files. Interestingly, when I relocate my tsconfig.json file from the root folder ...

Update header component dynamically upon successful login with Angular 11

I am currently using Angular 11 and facing an issue with displaying the username in the header component. The header loads before the login component, which results in the user data being stored in local storage only after the login component is loaded. As ...

Incorporating Angular 4 with Angular CLI and ASP.Net MVC5 for seamless integration

Creating a hybrid application with Angular 4 and MVC 5 is my current project. I've set up the Angular 4 structure using angular-cli, but most of the information online only covers either: Manually integrating the two technologies, or Integrating MVC ...

Executing the pause() function of NgbCarousel in Angular 5 when calling ngOnInit

I recently started learning Angular and using ngbootstrap for my UI development. I am facing an issue with loading the NgbCarousel in pause mode by default. Below is the code snippet that I have attempted: import { Component, OnInit, ViewChild } from ...

"Navigate to another screen with the FlatList component upon press, displaying specific

I've created a flatlist of countries with a search filter using an API. I need help implementing a feature where clicking on a country's name in the list redirects to a screen that displays the country's name and number of cases. The screen ...

Require a property to be mandatory depending on the value of another property within a generic interface

Looking for a way to have one property affect the others in a react component interface? Here's an example of what I'm trying to achieve: export interface IMyAwesomeComponentProps<T = {}> { className: string defaultPath?: ISomeOthe ...

Is it true that Node.js can be used to run Angular and Ionic frameworks

During a conversation about performance, the following question came up: Do Angular and Ionic require Node.js to be served, or is it sufficient to just serve the dist folder on the client side app? Is Node.js purely a development tool, or is it also used ...