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);
    }
}
                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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With