Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 - EXCEPTION: _this.subscribe is not a function - Custom validation

I'm trying to implement a custom validation rule to validate if a checkbox is checked.

But I'm getting an error

error_handler.js:46 EXCEPTION: _this.subscribe is not a function

When I try to add the custom validator

validator.ts

 import {Control} from "angular/common";

 interface ValidationResult {
     [key: string]: any;
 }

 export class CustomValidators {

     static validateChecked(c: Control): ValidationResult {
         return (c.value);
     }
 }

Component.ts

import {Component} from '@angular/core';

import {FormBuilder, FormGroup, Validators, FormControl} from '@angular/forms';
import {CustomValidators} from './validators.ts'

@Component({
    selector: 'wizard',
    templateUrl: './template.html',
})

/**
 * @todo - check how first select is automatically active
 * @todo - export form presets to form class
 */
export class Wizard {
    myForm: FormGroup;

    privacy: boolean;


    // Prefilling the FormBuilder
    constructor(private horizonService: HorizonService, fb: FormBuilder) {
        this.myForm = fb.group({
            'privacy': ['', Validators.required, CustomValidators.validateChecked],
        });
    }

    onSubmit(values: string): void {
        console.log('you submitted value: ', values);
    }
}
like image 222
Chalkin Avatar asked Sep 26 '16 11:09

Chalkin


2 Answers

You should use Validators.compose if you need more than one validator. So your code should be like this:

constructor(private horizonService: HorizonService, fb: FormBuilder) {
    this.myForm = fb.group({
      'privacy': ['', Validators.compose([Validators.required, CustomValidators.validateChecked])],
    });
  }

You can read a great article about validators here.

like image 169
Ledzz Avatar answered Oct 18 '22 21:10

Ledzz


I think that if you change around your FormGroup constructor a bit, by passing in a new FormControl() and adding the Validators to an array, it may well work.

Something Like:

export class Wizard {
    myForm: FormGroup;

    constructor(private horizonService: HorizonService) {
        this.myForm = new FormGroup({
            privacy: new FormControl('', [
                Validators.required,
                CustomValidators.validateChecked
            ])
        });
    }
}

I recommend taking a read through this post on CUSTOM VALIDATORS IN ANGULAR 2.

Regards.

like image 24
P. Moloney Avatar answered Oct 18 '22 21:10

P. Moloney