After creating a custom validator, I implemented it in my Angular project like this:
import { AbstractControl, ValidationErrors, ValidatorFn } from "@angular/forms";
export function notInSet(theSet: Set<string>): ValidatorFn {
return (control: AbstractControl): ValidationErrors | null => {
const val = control.value;
if(theSet.has(val))
return {InSet: true};
else
return null;
}
}
Next, in the template file, I added the usage of the custom validator to validate user input:
<form #myForm novalidate>
<input pInputText [(ngModel)]="name" name="name" notInSet="existingNames" #theName="ngModel"/>
<div *ngIf="!theName.valid" class="text-error">
Please provide a unique name for this API
</div>
</form>
In this code snippet, the variables existingNames
and name
are defined in the corresponding TypeScript file.
However, despite implementing the custom validator, it seems that the validation function is never triggered. I suspect that I need to register it in a specific location within the Angular application, but I'm uncertain about where exactly that should be.