Issue with custom validator not functioning correctly within a template-driven form

I have encountered an issue while trying to implement a custom validator in a template-driven form within my Angular project. It seems that the ngModel is not recognizing the custom validator. Can you help me identify what might be causing this problem?

The custom validator code is as follows:

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

function usernameExistsFactory(): ValidatorFn {
  return (c: AbstractControl) => {
    let isValid = c.value === 'Juri';

    if (isValid) {
      return null;
    } else {
      return {
        usernameExists: true
      };
    }
  };
}
@Directive({
    selector: 'usernameExistsValidator',
    providers: [
      { provide: NG_VALIDATORS, useExisting: usernameExistsValidator, multi: true }
    ]
  })
  export class usernameExistsValidator implements Validator {
    validator: ValidatorFn;
    
    constructor() {
      this.validator = usernameExistsFactory();
    }
    
    validate(c: FormControl) {
      return this.validator(c);
    }
    
  }

The input element where the custom validator should be applied is as shown below:

<input (change)="log(name)" required usernameExistsValidator ngModel minlength="3" maxlength="32" name="name" #name="ngModel" type="text"  class="form-control" id="name">

Upon inspection, the ngModel does not seem to be registering the validation properly.

Answer №1

When utilizing an attribute selector for your directive, it is crucial to remember to enclose the attribute within brackets [....]. Therefore, make sure to adjust your directive selector as follows:

selector: '[usernameExistsValidator]'

This rule applies universally whenever employing an attribute selector, not just in this specific scenario.

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

Reselect.createSelector() function in Typescript compiler returns incorrect type definition

It seems that the .d.ts file for reselect (https://github.com/reactjs/reselect) is accurate. So why am I experiencing issues here... could it be a problem with the Typescript compiler or my tsconfig? To replicate the problem: Demo.ts import { createSele ...

Select all entities in TypeORM except for the ones where the id is not equal to a specific condition

In my scenario, I am dealing with two entities: @Entity() export class Point { @PrimaryGeneratedColumn('uuid') id: string; // some other stuff } @Entity() export class Product { ...

When attempting to send file data in a $http Post request in Angular 8, the Rails API logs show an empty object {}

Using Angular 8 with a Rails 5.2 API I am currently attempting to add an image attachment feature to my Event model in the edit form. I have been following instructions from this specific tutorial Below is a snippet of my TypeScript code: const httpOpti ...

Tips on refreshing asset information within a live Angular application

I am currently managing an Angular project on a web server. The server houses python scripts that run periodically to generate a .json file. This latest version of the .json file replaces the existing one in the assets folder of the project (dist/test/asse ...

Encountered an issue when making an Angular2 HTTP POST request - SyntaxError: JSON input unexpectedly ended

Encountering an issue while trying to post data from Angular2 to a NodeJS backend. Although the POST request is successful and the server logs the correct data, an error is displayed in the browser: An error occurred: SyntaxError: JSON.parse: unexpected ...

Automatic type inference is activated while employing intricate "isEmpty" verification

I have created a customized function similar to Ramda's isEmpty, tailored to meet my specific requirements: /** * Checks if a value is empty. * Returns true for null, undefined, empty strings, empty Sets, empty Maps, and objects without properties. ...

What is the reason for ngbDatepicker converting numbers into dates upon input?

This specific HTML snippet has a unique feature: when the input number is set to "2", it automatically changes to 04.01.2001: <div class="input-group"> <input [ngClass]="{'invalid-input': editFor ...

Accessing state from ngrx in Angular and executing an HTTP request

When working on a service, I encountered an issue where I needed to retrieve data from the redux store and utilize it in an http request. However, I kept encountering errors or the http request was not being executed as expected. Here is the code snippet o ...

Guide to utilizing services in Angular 2

As I've developed a service with numerous variables and functions, my goal is to inject this service into multiple components. Each component should have the ability to update certain variables within the service so that all variables are updated once ...

Adjust the appearance of the ion-toggle by using a variable that can be set to either true or false for

It seemed like everything was working, but I hit a roadblock. For some reason, I can't figure out how to dynamically change the visual value of my ion-toggle using a variable number. Even though I initialize my app with the variable set to false, th ...

Encountering an issue during Angular upgrade from version 8 to 11: Error message stating that the class extends value is undefined,

I am currently in the process of upgrading my Angular application from version 8 to 11, but I encountered the following error: Uncaught TypeError: Class extends value undefined is not a constructor or null at Module.4lR8 (main.js:sourcemap:59) at _ ...

Error: It is not possible to assign a value to the Request property of the Object since it only has a getter method

Encountering issues while attempting to deploy my Typescript Next.js application on Vercel. The build process fails despite functioning correctly and building without errors locally. Uncertain about the root cause of the error or how to resolve it. The f ...

Reset form fields after submission using vuex

I am having trouble clearing a form after submitting it to create a new user. I am using Vuex to reset the state, but for some reason, the form still retains the data. This is what the form looks like: <form @submit.prevent="onSubmit" v-if=&q ...

Discover the potential of JavaScript's match object and unleash its power through

In the given data source, there is a key called 'isEdit' which has a boolean value. The column value in the data source matches the keys in the tempValues. After comparison, we check if the value of 'isEdit' from the data source is true ...

Using Angular's ag-grid to establish gridOptions based on @input values

Objective: Develop a wrapper component for ag-grid-angular used to set gridOptions with data from @input. //wrapper component // .html <ag-grid-angular [gridOptions]="gridOptions" [columnDefs]="..." [rowData]="..."> </ ...

Nx workspace combined with the use of localstorage for data storage

Currently, I am working on a project that involves utilizing Nrwl Nx workspace to maintain a unified codebase across various applications (web, ionic 4, electron). I am seeking advice on the best approach to incorporate local storage functionality in ...

The reducer with typing indicated that it is only able to process the type of "never."

I'm currently working on implementing a typed reducer for creating a slice. To start, I define the IFeatureState interface and initialState as follows: interface IFeatureState { content: string; open: boolean; } const initialState: IFeatureState ...

Leveraging html form submit to transmit data to php and retrieving it via javascript

I'm attempting to transmit data from an HTML form to PHP, where JavaScript will then extract the information. Below is the code for my HTML form: <form action="search.php" method='POST'> <input id="movie_name" name="movie_name ...

Angular2: Is unsubscribing from host listeners necessary? How do host listeners function? If I don't need to unsubscribe, under what circumstances are they automatically unsubscribed?

@HostListener('window:scroll', ['$event']) onScroll(event) { // Handling scroll event } I have implemented a 'onScroll' function to listen for scroll events in various components. I haven't included an unsubscrib ...

What's Going on with My Angular Dropdown Menu?

Snippet of HTML code: <li class="nav-item dropdown pe-3"> <a class="nav-link nav-profile d-flex align-items-center pe-0" (click)="toggleProfileMenu()"> <img src="assets/img/profile-img.jpg" alt=& ...