Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access service from Custom Validator in Angular

I'm trying to access my service in order to make check for the validator but all i get is console full of errors I'm sure I'm just bad with syntax stuff =/

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 even another solution to make the custom validation in the component itself I would like any help.. thanks!

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)
like image 911
hindi1991 Avatar asked Oct 06 '18 21:10

hindi1991


People also ask

What must be returned from a custom validator function?

The validator function needs to return null if no errors were found in the field value, meaning that the value is valid.

What is custom validator in Angular?

A validator in Angular is a function which returns null if a control is valid or an error object if it's invalid. For model-driven forms we create custom validation functions and pass them into the FormControl constructor.

What method should you implement for your custom validator?

Implementing the Validator Interface A Validator implementation must contain a constructor, a set of accessor methods for any attributes on the tag, and a validate method, which overrides the validate method of the Validator interface.

What is Updateon in Angular?

When using Angular Forms, by default, on every keystroke, the values of your form controls are updated and their associated validators are executed. This may not be always desirable.


1 Answers

You have to pass the service to the validator, there is no dependency injection here as this is not an Angular directive, it is a pure function. The way to do this is to use a factory method that accepts the service and creates a validator function.

export function titleValidator(dataService:DataService): ValidatorFn {
  return (control: AbstractControl) => {
    console.log(dataService.moviesArray) // now you can :)

    // Test for control.value only, for eg:
    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,
         titleValidator(this.dataService)
  ]],
  ...
});

There is no need to check for the presence of control as Angular only calls the validator function with a valid control. Test only the value. More info here

like image 85
Avin Kavish Avatar answered Nov 14 '22 23:11

Avin Kavish