Shahar Shokrani
Shahar Shokrani

Reputation: 8762

FormControl validator always invalid

Following my previous question, I'm trying to create a custom validator that allow the users to type only specific values in an input of text.

app.component.ts:

export class AppComponent implements OnInit {
  myForm: FormGroup;
  allowedValuesArray = ['Foo', 'Boo'];

  ngOnInit() {
    this.myForm = new FormGroup({
      'foo': new FormControl(null, [this.allowedValues.bind(this)])
    });        
  }

  allowedValues(control: FormControl): {[s: string]: boolean} {
    if (this.allowedValuesArray.indexOf(control.value)) {
      return {'notValidFoo': true};
    }        
    return {'notValidFoo': false};
  }
}

app.component.html:

<form [formGroup]="myForm">
  Foo: <input type="text" formControlName="foo">
  <span *ngIf="!myForm.get('foo').valid">Not valid foo</span>
</form>

The problem is that the foo FormControl is always false, (the myForm.get('foo').valid is always false).

enter image description here

What wrong with my implementation?

Upvotes: 1

Views: 1243

Answers (1)

PushpikaWan
PushpikaWan

Reputation: 2545

you just need to return null when validation is ok. and change that method like below

private allowedValues: ValidatorFn (control: FormControl) => {
    if (this.allowedValuesArray.indexOf(control.value) !== -1) {
        return {'notValidFoo': true};
    }
    return null;    
}

Upvotes: 3

Related Questions