Angular2 Uniqueness Validator: Ensuring Data Integrity

Within my Angular2 form field, I am trying to ensure that the inputted value does not already exist. The challenge lies in accessing instance members within my custom validator function, codeUnique(). Upon execution, "this" refers to either FormControl or undefined, leaving my validator function devoid of context and instance variables. How can I pass my existing values list into my validator without resorting to placing them in a global scope?

import { Component, Input, Output, EventEmitter } from '@angular/core';
import { NG_VALIDATORS, FormControl, FormBuilder, FormGroup, Validators, AbstractControl } from '@angular/forms';

import { ReferringAppModel } from './referringapp.model';
//import { CodeValidator } from './code-validator';

@Component({
    selector: 'add-client-form',
    templateUrl: 'src/home/add-client-form.component.html'
})
export class AddClientFormComponent {
    myForm: FormGroup;
    code: AbstractControl;
    name: AbstractControl;

    constructor(fb: FormBuilder) {
        this.myForm = fb.group({
            'code': ['', this.codeUnique],
            'name': ['', Validators.required]
        });
        this.code = this.myForm.controls['code'];
        this.name = this.myForm.controls['name'];
    }
    @Input() referringApps: ReferringAppModel[];

    ngOnInit() {
    }
    onSubmit(form: any): void {
        console.log("submitted")
    };

    codeUnique(c: FormControl) {
        try {
            // Blows up. 
            return !this.referringApps.find(appInApps => appInApps.Code == c.value) ? null : {
                //return false ? null : { // WORKS
                validateEmail: {
                    valid: false
                }
            };
        } catch (ex) {
            console.log(ex);
        }
    }
}


TypeError: Cannot read property 'referringApps' of undefined
    at AddClientFormComponent.codeUnique (http://localhost/HubHacienda/dist/bundle.js:50071:26)
    at http://localhost/HubHacienda/dist/bundle.js:43538:54
    at Array.map (native)
    at _executeValidators (http://localhost/HubHacienda/dist/bundle.js:43538:28)
    at FormControl.Validators.compose [as validator] (http://localhost/HubHacienda/dist/bundle.js:43518:38)
    at FormControl.AbstractControl._runValidator (http://localhost/HubHacienda/dist/bundle.js:45083:54)
    at FormControl.AbstractControl.updateValueAndValidity (http://localhost/HubHacienda/dist/bundle.js:45061:38)
    at FormControl.setValue (http://localhost/HubHacienda/dist/bundle.js:45327:19)
    at DefaultValueAccessor.onChange (http://localhost/HubHacienda/dist/bundle.js:44287:22)
    at DebugAppView._View_AddClientFormComponent0._handle_input_12_0 (AddClientFormComponent.ngfactory.js:493:47)
    at DebugAppView.eventHandler (http://localhost/HubHacienda/dist/bundle.js:35576:29)
    at COMPONENT_REGEX (http://localhost/HubHacienda/dist/bundle.js:38521:41)
    at http://localhost/HubHacienda/dist/bundle.js:38634:116
    at ZoneDelegate.invoke (http://localhost/HubHacienda/dist/bundle.js:6875:29)
    at Object.onInvoke (http://localhost/HubHacienda/dist/bundle.js:32132:42)
    at ZoneDelegate.invoke (http://localhost/HubHacienda/dist/bundle.js:6874:35)
    at Zone.runGuarded (http://localhost/HubHacienda/dist/bundle.js:6782:48)
    at NgZoneImpl.runInnerGuarded (http://localhost/HubHacienda/dist/bundle.js:32161:83)
    at NgZone.runGuarded (http://localhost/HubHacienda/dist/bundle.js:32393:78)
    at HTMLInputElement.outsideHandler (http://localhost/HubHacienda/dist/bundle.js:38634:84)
    at ZoneDelegate.invokeTask (http://localhost/HubHacienda/dist/bundle.js:6908:38)
    at Zone.runTask (http://localhost/HubHacienda/dist/bundle.js:6808:48)
    at HTMLInputElement.ZoneTask.ZoneTask.cancelFn.invoke (http://localhost/HubHacienda/dist/bundle.js:6976:34)

Answer №1

It's quite straightforward: when you set the validator, make sure to connect the this parameter of your class to it by using:

'code : ['', this.codeUnique.bind(this)]

Answer №2

customValidation = (c: FormControl) => {
    // Enter your custom validation logic here
 }

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

what kind of bespoke entity in TypeScript

Exploring typescript for the first time, I have constructed this object: const startingState = { name: { value: "", error: false }, quantity: { value: 0, error: false }, category: "Grocery& ...

How can I extract just the initial 2 letters of a country name using AmCharts maps?

Having trouble with Amcharts maps. I have a map that displays countries as United States, but I only want them to show as US. Is there a country formatter available for this issue? Any help is appreciated. ...

Unable to direct XHR requests even though the URL is functional in the browser

I am currently working on developing a REST API in TypeScript using NodeJS and Express. So far, the API is up and running on localhost. When I visit http://localhost:8080, everything functions as expected. Specifically, I have configured the route http:/ ...

Encountered a Next-Auth Error: Unable to fetch data, TypeError: fetch failed within

I've been struggling with a unique issue that I haven't found a solution for in any other forum. My Configuration NextJS: v13.0.3 NextAuth: v4.16.4 npm: v8.19.2 node: v18.12.1 When the Issue Arises This particular error only occurs in the pr ...

Error: The current call does not match any existing overloads - TypeScript, NextJS, styled-components

I'm facing an issue while trying to display icons in the footer of my website. The error message "Type error: No overload matches this call" keeps appearing next to my StyledIconsWrapper component, causing Vercel deployment to fail. Despite this error ...

The CanActivate route guard in Angular Router never seems to return a true value

I'm facing an issue with using CanActivate to protect a page, as it always returns false and I can't access the protected router. Despite trying various solutions, I haven't been able to resolve the problem yet. Being new to angular, I' ...

Utilizing Office.js: Incorporating Angular CLI to Call a Function in a Generated Function-File

After using angular-cli to create a new project, I integrated ng-office-ui-fabric and its dependencies. I included in index.html, added polyfills to angular.json, and everything seemed to be working smoothly. When testing the add-in in Word, the taskpane ...

How can RxJS be used to handle only the first value returned when calling multiple URLs?

I am faced with the challenge of having multiple URLs containing crucial information. My goal is to find a specific ID within these URLs, but I do not know which URL holds the necessary details. The approach I'm taking involves calling each URL and us ...

identifiers that have been duplicated errors

My journey with VS 2017 and angular 2 started off smoothly, but I hit a roadblock when I encountered 352 errors upon restarting my machine. The errors were mostly "Duplicate Identifier errors," and after some investigation, I realized that I had the file i ...

Switch button - reveal/conceal details

I am looking for assistance in toggling the visibility of information when clicking on an arrow icon. I have attempted to use JavaScript, but it was unsuccessful. My goal is to hide the information below by clicking on the downward-facing arrow image , an ...

How to Add a Rule to an Existing Application Load Balancer Listener using AWS CDK

When I inherited a project, I discovered an application load balancer with a HTTPS Listener that was set up before I began using CDK. This listener currently has 13 rules in place that route requests based on hostname to different fargate instances, with ...

Exploring Angular observables: Tips for gathering specific fields from a nested array within an object into a new array

I am working on parsing a JSON object and extracting specific fields to create their own array. My goal is to loop through the provided object and gather the 'appSupportedId' values into a separate array. An issue has arisen, leading to an ERRO ...

Troubleshooting Angular 2 routerLink functionality issues

I have gone through all the tutorials and still can't figure out what I am doing wrong. AppModule : import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { FormsModule } fr ...

Retrieve upcoming route details within canDeactivate guard in the updated Angular2 router

Is there a way to retrieve the upcoming route information within the "canDeactivate" guard of Angular 2's new router? ...

Monitoring modifications in elements within an array using Angular2

Currently using Angular 2 and typescript, I have an array in which I am utilizing DoCheck and IterableDiffer to monitor any changes. While I receive notifications when the array itself is modified, I do not get notified if a property within one of the obje ...

Problem with custom anchor component in React that needs to perform an action before being clicked

React Component (Custom Anchor) import React from 'react'; class Anchor extends React.Component { onClick = (event) => { // ----------------------------- // send Google Analytics request ...

The "ngx-phone-select" directive is not defined with the "exportAs" attribute

Having an issue with ngx-phone-select in the phone number field, receiving the error message "There is no directive with "exportAs" set to "ngx-phone-select" http://prntscr.com/hzbhfo This problem occurs in Angular 4.3 using ngx-phone-select version 1.0. ...

Ag-grid allows for the creation of multiple individual detail grids that are connected to a single

I noticed in the ag-grid documentation that all the master/detail examples feature only a single detail grid implementation. Is it possible to incorporate multiple (different) detail grids within one master grid, specifically in one row? ...

Protected Node.js API paths

Recently, I was developing a login with OTP feature for my app. The front-end is being built using Angular and the back-end on ExpressJs. However, I have been struggling to find a way to secure the API. Every time I test the API using Postman, it works per ...

Transmit data to a modal popup in Angular 8

Here is the code snippet written in .ts file: openFormModal(id: number) { console.log(id); const modalRef = this.modalService.open(PartidoComponent); modalRef.componentInstance.id = id; //modalRef.componentInstance.id = id; modalRef.r ...