I created a personalized validator for the phone field but I'm encountering
an issue
The validator should be returning either a Promise or an Observable.
Basically, I just want to check if the phone number is less than 10 characters.
HTML Code Snippet
<div class="form-group col-xs-3 col-md-3"
[ngClass]="{
'has-error':(ersaForm.get('phone').touched || ersaForm.get('phone').dirty ) &&
!ersaForm.get('phone').valid
}">
<label for="phoneId" class="control-label">Phone</label><br />
<p-inputMask mask="(999) 999-9999" formControlName="phone" inputStyleClass="form-control" [style]="{'width': '100%','height':'34px'}" id="phoneId" placeholder="Phone (required)"></p-inputMask>
<span class="help-block" *ngIf="(ersaForm.get('phone').touched || ersaForm.get('phone').dirty ) &&
ersaForm.get('phone').errors">
<span *ngIf="ersaForm.get('phone').errors.phonePBXCheck">
Invalid Phone Number.
</span>
</span>
</div>
TypeScript Function
function verifyPhone(phone: string): ValidatorFn {
return (c: AbstractControl): { [key: string]: boolean } | null => {
var phoneNumber = c.value;
phoneNumber = phoneNumber.replace('(', '');
phoneNumber = phoneNumber.replace(')', '');
phoneNumber = phoneNumber.replace('-', '');
phoneNumber = phoneNumber.replace('_', '');
phoneNumber = phoneNumber.replace(' ', '');
console.log('custom validation ' + phoneNumber);
if (c.value != undefined && isNaN(c.value) || phoneNumber.length < 10) {
return { 'phonePBXCheck': true };
};
return null;
};
}
this.ersaForm = this._fb.group({
phone: ['', Validators.required, verifyPhone('')],
});
What Could Be Missing Here?