I am working on learning Angular 5 reactive forms and have tried to make an example custom validator that displays an error message on the form. When I try to type anything in the project name field (called "namey" here), I get this exception (the line number given is just pointing to the start of the input in the HTML):
AppComponent.html:20 ERROR TypeError: Cannot read property 'cannotBeTestx' of null
at Object.eval [as updateDirectives] (AppComponent.html:27)
at Object.debugUpdateDirectives [as updateDirectives] (core.js:14338)
at checkAndUpdateView (core.js:13507)
at callViewAction (core.js:13857)
at execComponentViewsAction (core.js:13789)
at checkAndUpdateView (core.js:13513)
at callWithDebugContext (core.js:14739)
at Object.debugCheckAndUpdateView [as checkAndUpdateView] (core.js:14276)
at ViewRef_.detectChanges (core.js:11299)
at eval (core.js:5783)
Here is the component code:
ngOnInit() {
this.projectForm = new FormGroup({
namey: new FormControl(null, [Validators.required, this.cannotBeTest1]),
email: new FormControl(null, [Validators.required, Validators.email]),
status: new FormControl('1')
});
}
Here is the custom validator code:
cannotBeTest1(control: FormControl): {[s: string]: boolean} {
const name: string = control.value;
if (name && name.toLowerCase() === 'test') {
return {'cannotBeTestx': true};
} else {
return null;
}
}
Here is the HTML for this element (there are a couple of other form elements that are working fine and after that is a closing form tag):
<form class="ui form-vertical" [formGroup]="projectForm" (ngSubmit)="onSubmit()">
<div class="form-group">
<label for="project-name">project Name</label>
<input
class="form-control"
type="text"
id="project-name"
placeholder="Enter project name"
formControlName="namey"
/>
<span class="help-block" *ngIf="projectForm.get('namey').errors['cannotBeTestx'] && (projectForm.get('namey').touched || formSubmitted)">-->
please enter a valid project name
</span>
<span class="help-block" *ngIf="!projectForm.get('namey').valid && (projectForm.get('namey').touched || formSubmitted)">
please enter a project name
</span>
</div>
I have been messing with things, renaming stuff and come down to this part of the error display being the issue:
projectForm.get('namey').errors['cannotBeTestx']
Interestingly, if I remove that error message display in the HTML, the custom validator works correctly (I can't make the project name "test") and I get the other, generic error message display. So it seems to be something about the way I am checking to see if that custom validator is invalid but I can't for the life of me figure out what it is.
Thank you for any help!