Utilizing Custom Validators in Angular to Enhance Accessibility

I'm struggling to access my service to perform validator checks, but all I'm getting is a console filled with errors. I believe it's just a syntax issue that's tripping me up.

Validator:

import { DataService } from './services/data.service';
import { AbstractControl, FormGroup } from '@angular/forms';

export function titleValidator(control: AbstractControl,dataService:DataService) {

    console.log(dataService.moviesArray) -->> How can I access this service?
    if (control && (control.value !== null || control.value !== undefined)) {
        if (control.value=="test") {
            return {
                isError: true
            };
        }
    }

    return null;
}

Component:

this.movieForm = this.fb.group({
      title: ['', [Validators.required,titleValidator]],
      ...
    });
  }

If anyone has an alternative solution for implementing custom validation within the component, any assistance would be greatly appreciated. Thank you!

Update: The Errors:

AddMovieComponent_Host.ngfactory.js? [sm]:1 ERROR TypeError: Cannot read property 'moviesArray' of undefined
    at titleValidator (validator.ts:8)
    at forms.js:602
    at Array.map (<anonymous>)
    at _executeValidators (forms.js:602)
    at FormControl.validator (forms.js:567)
    at FormControl.push../node_modules/@angular/forms/fesm5/forms.js.AbstractControl._runValidator (forms.js:2510)
    at FormControl.push../node_modules/@angular/forms/fesm5/forms.js.AbstractControl.updateValueAndValidity (forms.js:2486)
    at new FormControl (forms.js:2794)
    at FormBuilder.push../node_modules/@angular/forms/fesm5/forms.js.FormBuilder.control (forms.js:5435)
    at FormBuilder.push../node_modules/@angular/forms/fesm5/forms.js.FormBuilder._createControl (forms.js:5473)

Answer №1

In order to utilize the service within the validator, you must pass it as a parameter since there is no dependency injection available in this context, unlike Angular directives which support it. To achieve this, a factory method can be implemented that takes the service and generates a validator function.

export function customValidator(dataService:DataService): ValidatorFn {
  return (control: AbstractControl) => {
    console.log(dataService.moviesArray) // Access data from service here

    // Check control.value against moviesArray for example:
    if (control.value && dataService.moviesArray.includes(control.value))
      return null;
    else
      return { 'movieNotFound' : { value: control.value } };
  }
}

Usage:

this.movieForm = this.fb.group({
  title: ['', [
         Validators.required,
         customValidator(this.dataService)
  ]],
  ...
});

No need to verify the presence of the control object as Angular guarantees its validity when calling the validator function. Focus solely on testing the value. Additional information can be found 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

Discovering the country associated with a country code using ngx-intl-tel-input

In my application, I am trying to implement a phone number field using this StackBlitz link. However, I have observed that it is not possible to search for a country by typing the country code (e.g., +231) in the country search dropdown. When I type a coun ...

What's the trick to efficiently managing multiple checkboxes in an array state?

I have a lengthy collection of checkboxes that is not well optimized. I am trying to obtain the checked ones and store them in an array state. However, I am uncertain about how to handle this situation and I would appreciate some assistance. It should also ...

Issue with Tooltip Position when Scrolling Sidebar is causing display problems

My goal is to create a Sidebar with Tooltip attached to its <li> elements similar to this example: Screenshot - Good Tooltip However, I am facing an issue where the position of the Tooltip breaks when scrolling to the bottom of the sidebar, causing ...

Utilize Next JS pages api to generate dynamic routes based on unique ids

In the content of my website, there is a collection of objects named stories that are displayed as an array. Additionally, I have a section where each individual story is showcased in detail. I intend to enable users to click on any story link within the ...

Steps for displaying a new event on a fullCalendar

Utilizing fullCalendar to display a list of events in the following manner: this.appointments = [{ title: "Appointment 1", date: "2020-09-06", allDay: false }, { title: "Appointment 2", date: "2020 ...

When attempting to create a build using npm run, an error with code ELIFECYCLE occurred despite successfully installing

I've been attempting to run the lodash library on my computer. You can find the library here on GitHub. I went ahead and forked the repository, then cloned it onto my system. I successfully installed all dependencies mentioned in the package.json fil ...

Exploring Next.js 13: Enhancing Security with HTTP Cookie Authentication

I'm currently working on a web app using Next.js version 13.4.7. I am setting up authentication with JWT tokens from the backend (Laravel) and attempting to store them in http-only cookies. Within a file named cookie.ts, which contains helper functio ...

Validation of Angular 5 forms for detecting duplicate words

I need help with a basic form that has one input. My requirement is to validate that the user does not input an existing word. If the user does enter an existing word, I would like to display a message below the input field saying "This word already exis ...

Are non-local variables in Node.js considered safe to use?

Would it be secure to implement this code in Node.js/Express.js? // using Object.create(null) to avoid key collisions // refer http://www.devthought.com/2012/01/18/an-object-is-not-a-hash/ var theHash = Object.create(null); exports.store = function (req, ...

Utilizing Cookies within an HTML Page

My current code is functioning perfectly, accurately calculating the yearly income based on the input "textmoney." I have a link to a more advanced calculator for a precise prediction. My goal is to find a way for the website to retain the data input from ...

React Foundation accordion not functioning properly

Utilizing Foundation accordion within my React component has presented a challenge. The code functions properly when rendering static HTML, but when attempting to render it dynamically through a loop, the accordions lose their clickability. React code fo ...

Develop a cutting-edge Drag and Drop Functionality using the innovative Material CDK

Here is a unique link you can check out: https://stackblitz.com/angular/nabbkobrxrn?file=src/app/cdk-drag-drop-enter-predicate-example.ts. In this example, I have specific goals: I want to be able to select only one number from the "Available numbers" l ...

Revive your Chart JS visualization with interactive re-animation via onclick action!

I've been exploring Chart.js and trying to achieve something simple, but I'm having trouble. I just want the chart to re-animate when clicking on a button, but I can't seem to make it work. I attempted to attach chart.update to the onclick e ...

Sharing Pictures and Messages using angular, express, and multer

Struggling with posting images and text to the server while self-learning Angular. The backend works fine in Postman testing, but fails when working with Angular. Here is the code snippet I have been using: upload.component.html <form [formGroup]="upl ...

"Enhancing User Experience with AngularJS by Dynamically Modifying and Refresh

I'm currently attempting to dynamically add HTML elements using JavaScript with a directive: document.getElementsByClassName("day-grid")[0].innerHTML = "<div ng-uc-day-event></div>"; or var ele = document.createElement("div"); ele.setAttr ...

How can I fetch and reference multiple local JSON files in Vue using Axios?

I am currently utilizing vue for prototyping some HTML components. Is there a method to make Vue detect two separate JSON files? vue.js var vm = new Vue({ el: '#douglas-laing', data: { products: [], contentPanels: [] }, created() ...

Using an additional router-outlet in an Angular 2 application: a step-by-step guide

I have been facing an issue with my angular2 app where I am attempting to use 2 router-outlets. Despite reading numerous blogs and conducting multiple Google searches, I have not been able to make it work. I would greatly appreciate any suggestions on why ...

Activate Popover with Hover and simply click anywhere to dismiss

Currently utilizing Bootstrap 4 and intrigued by the popover feature that activates on hover and closes when clicked anywhere. I'm also interested in making links functional within the popover. Any suggestions or tips on how to achieve this? $(doc ...

The array is devoid of any elements, despite having been efficiently mapped

I'm facing some challenges with the _.map function from underscore.js library (http://underscorejs.org). getCalories: function() { var encode = "1%20"; var calSource = "https://api.edamam.com/api/nutrition-data?app_id=#&app_key=#"; _.m ...

Delete any HTML content dynamically appended by AJAX requests

I'm currently working on a page dedicated to building orders, where the functionality is fully dependent on ajax for finding products and adding them dynamically. However, I encountered an issue when attempting to remove an item that was added via aj ...