0

I'm trying to create a simple custom validator. basically if one variable (behalf) is true, the field must be mandatory. That's all.

I don't know why, but I cannot read the variable behalf. It's throw undefined. Any clue about how to handle this ?

behalf = false;
private validateName(){
    if (this.behalf && this.nameB.text != '') {
        return {
            invalidName : true
        };
    }
    else{
        return null;
    }
}    
constructor (private builder: FormBuilder){
    this.title = new Control('', Validators.required);
    this.name = new Control('', this.validateName);
    this.type = new Control('', Validators.required);
    this.desc = new Control('');
    this.hideTitle = new Control('');
    this.end = new Control('', Validators.required);
    this.formBook = builder.group({
        title: this.title,
        name: this.name,
        type: this.type,
        desc: this.desc,
        hideTitle: this.hideTitle,
        end: this.end
    });
}

2 Answers 2

3

The problem is that you reference a function so the this doesn't correspond to the component object when this function is called.

You could try the following to force the execution of the function in the context of the component instance:

this.name = new Control('', (control) => {
  this.validateName(control);
});

or using the bind method:

this.name = new Control('', this.validateName.bind(this));

Be careful when using the bind method in TypeScript:

Sign up to request clarification or add additional context in comments.

Comments

0

Hi I think This method is Useful To You.

addCustomerForm :any;
constructor (private builder: FormBuilder){

this.customername = new Control("", Validators.compose([Validators.required, 
ValidationService.alphaValidator]));

this.addCustomerForm = formBuilder.group({
     customername: this.customername,
 });

 this.customerName = '';

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.