How to pass Form Control value to custom Validator Function's Parameter in Angular 5 Reactive Forms

How to pass Form Control value to custom Validator Function's Parameter in Angular 5 Reactive Forms

Content Index :

How to pass Form Control value to custom Validator Function's Parameter in Angular 5 Reactive Forms
Tag : angular , By : Michael Gunderson
Date : November 28 2020, 04:01 AM

Does that help You have to wrap it in a private form field which contains an arrow function, otherwise it's executed at component creation, instead of validation:
export class CategoryFormComponent {
  private categoryValidator = (control: AbstractControl) => {
    return this.checkCategoryInput(control.value, this.categoryList);

  this.whatHappenedFormGroup = this.formBuilder.group({
    reason: ['', Validators.compose([Validators.required])],
    category: ['', Validators.compose([

No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

Angular2 how to pass a parameter into a custom form control validator?

Tag : angular , By : wiznick
Date : March 29 2020, 07:55 AM
I think the issue was by ths following , You can make the directive itself the validator. That way you can use the message input.
import { forwardRef } from '@angular/core';
import { Validator } from '@angular/forms';

  selector: '[checkbox-required-validator]',
  providers: [
      provide: NG_VALIDATORS,
      multi: true,
      useExisting: forwardRef(() => CheckboxRequiredValidator )
export class CheckboxRequiredValidator implements Validator {
  @Input('checkbox-required-validator') msg  = 'default message';

  validate(c: AbstractControl) {
    return c.value ? null : {
      required: this.msg

Angular 4: reactive form control is stuck in pending state with a custom async validator

Tag : javascript , By : Robby
Date : March 29 2020, 07:55 AM
I hope this helps . There's a gotcha!
That is, your observable never completes...
.map(data => {
   return data.status === 'invalid' ? { invalid: true } : null;

Custom Validator Control Quantity in Reactive Forms

Tag : angular , By : hlpimfalling
Date : March 29 2020, 07:55 AM
this one helps. the key is using "parent" to reach the formArray. then we can use map to transform the array and get only que quantity and reduce to get the sum of the quantities
customValidator(campo1: string) {
    return (group: FormGroup): { [key: string]: any } => {
      //get the formArray
      const form=(group.parent as FormArray);
      if (form)
        //get the available quantity using parent
        let available =form.parent.get('available_quantity').value;

        //the final available are the available less each quantity
        available=form.value //In form.value we have e.g. [{quantity:10..},{quantity:16}]
          .map(x=>x.quantity?+x.quantity:0)  //using map we have, e.g. [10,16]
          .reduce((a, b) => a - b, available)  //using reduce we substract the quantities to available
        if (available<0) {
          return {
            out: true

2 Custom validator not working in reactive forms in Angular

Tag : angular , By : Cenneca
Date : March 29 2020, 07:55 AM
fixed the issue. Will look into that further I figured out why your second validator does not work. In fact the adding of the validators is wrong.
You assigned your validators array as second parameter of the this.fb.group() method :
this.fb.group({...}, [this.subFormValidator.bind(this), { validator: this.AvailabilityBalanceValidator('available_qty', 'quantity') }];
this.fb.group({...}, {
    validator: Validators.compose([this.subFormValidator.bind(this), this.AvailabilityBalanceValidator('available_qty', 'quantity')])
subFormValidator(control: AbstractControl): { [key: string]: any } {
    return control.value.checkbox_value && 
        // Only adds the error if quantity is not set or it's an empty string
        (!control.value.quantity || control.value.quantity.length === 0)? { 'req': 'This field is required' } : null
<small class="form-text text-muted danger" *ngIf="row.hasError('req')">This field is required</small>

How to pass parameters to custom validator function in angular reactive form?

Tag : angular , By : mylonov
Date : March 29 2020, 07:55 AM
Does that help Thats because your value1 and value2 does not correspond to any at all. You need to send in the key instead of value1 and value2. Take the reference from below example.
Working Plunker: http://plnkr.co/edit/RlWslfyr1eiTq4MSc3iY?p=preview
import {Component, FormBuilder, Control, ControlGroup, Validators} from 'angular2/angular2'

  selector: 'my-app',
  template: `
    <form [ng-form-model]="form">
      <label for="name">Name:</label>
      <input id="name" type="text" ng-control="name">
        <div ng-control-group="matchingEmail">
      <label for="email">Email:</label>
      <input id="email" type="email" ng-control="email">
      <label for="confirmEmail">Confirm Email:</label>
      <input id="confirmEmail" type="email" ng-control="confirmEmail">
      <div ng-control-group="matchingPassword">
        <label for="password">Password:</label>
        <input id="password" type="password" ng-control="password">
        <label for="confirmPassword">Confirm Password:</label>
        <input id="confirmPassword" type="password" ng-control="confirmPassword">
    <p>Valid?: {{form.valid}}</p>
    <pre>{{form.value | json}}</pre>
export class App {
  form: ControlGroup
  constructor(fb: FormBuilder) {
    this.form = fb.group({
      name: [''],
        matchingEmail: fb.group({
        email: ['', Validators.required],
        confirmEmail: ['', Validators.required]
      }, {validator: this.fieldMatcher('email','confirmEmail')}),
      matchingPassword: fb.group({
        password: ['', Validators.required],
        confirmPassword: ['', Validators.required]
      }, {validator: this.fieldMatcher('password','confirmPassword')})

 fieldMatcher(value1: string, value2: string) {
  return (group: ControlGroup) => {
    if (group.controls[value1].value !==  group.controls[value2].value) {
      return group.controls[value2].setErrors({notEquivalent: true})

Related Posts Related QUESTIONS :
  • Matrix in FormGroup [Angular 2+]
  • "export 'DOCUMENT' was not found in '@angular/platform-browser'
  • angular autocomplete material
  • Prevent click event from triggering other click elements undernethe the front element
  • How to know when an image has been fully loaded in angular?
  • How to read config file to set API URL inside an Angular App packaged as a WAR and deployed on IBM Liberty
  • npm ERR! Unexpected end of JSON input while parsing near
  • override custom scss variable inside another angular-cli(7) (library) project
  • Angular-7 How to navigate to certain section of the single page website
  • how to disable an input field from a group of input fields in Angular
  • How to unit test selection of a mat-autocomplete option?
  • angular 8 form reset with value not working correctly
  • ng: error in production with Cb(...).firestore is not a function
  • Property 'result' does not exist on type 'EventTarget'
  • Cannot read property 'subscribe' of undefined on Ionic 4 , Angular 8
  • Repository is not clean. Please commit or stash any changes before updating In Angular 8
  • @angular-devkit/core module not found after angular-cli global fresh install
  • Lazy module loading error after updating to Angular 8
  • Using mat-tab-group focusChange event, How to stop user navigating to other tab
  • Best practice class member initialization
  • Angular 8 : TypeError: Found non-callable @@iterator
  • ng build --prod non-exported function
  • (Ionic4) How to dynamically go to previous page?
  • Angular 8.0.1 platform.es5.js:102 Uncaught TypeError: Object(...) is not a function
  • Zsh : command not found : ng on new Mac OS Catalina
  • Ag grid: How to add a row with sorting order
  • Failed to construct 'Worker': Module scripts are not supported on DedicatedWorker yet in Angular 8
  • How to write a function which will be return : Observable <ModelTemp>
  • cannot compile Ivy Rendering Engine in Angular 8
  • What is best way to apply ngif directive to <li> element?
  • Angular 7: Trigger valuechanges on addControl, if value's present
  • Function inside a ts file
  • Angular - Are admin files downloadable?
  • node_modules/@angular/cdk/table"' has no exported member 'CdkTextColumn'
  • node_modules/rxjs/Subject"' has no exported member 'Subject'
  • Angular - how to http service subscribe without response
  • how to test all my Service are injected into component
  • After upgrading to Angular8, AppEngine is serving scripts with the incorrect mime-type
  • Angular 6 - Cannot read property 'outlets' of null
  • Setting up background img with angular 7
  • Make BehaviorSubject persist across browser tabs? (@HostListener?)
  • Angular 7 : How to deploy Angular "Build" folder along with ASP.Net Web Api in Visual Studio 2017
  • How return name of image from FormControl in ReactivForms
  • Angular 7 HTTP Post 500 Internal Server Error
  • Ionic show data which is equal to the value
  • Angular directive inputs over component from another module cause an error
  • ValidationError: Progress Plugin Invalid Options
  • Angular mat-table : - Sort icon missing on custom sort
  • How use routing in angular correctly?
  • Automatic width mat-option in Angular Material
  • Angular Material Table how to pass object to displayedColumns instead of array
  • angular ngFor trackBy does not work as I expected
  • Module ag-grid-angular/main has no exported member AgGridNg2.ts
  • Angular 7 drag Drop swapping elements
  • datepicker' does not exist on type 'JQuery
  • Angular 7 - ERROR TypeError: Cannot read property 'positionChanges' of undefined for MatTooltip
  • Angular 7 LazyLoading with children of children
  • How to make ionic v4 alertbox message should route to other pages
  • Angular Material Tabs - Load/Unload components only when active tab is selected
  • RXJS Combining multiple observables inside a pipe
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com