Angular Custom Validator Error (Validation function must either return a Promise or an Observable)

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?

Answer №1

Modification: To ensure your validators work properly, make sure to wrap them in an Array.

 this.ersaForm = this._fb.group({
   phone: ['', [Validators.required, phoneCheck('')]],
 });

In addition, it is recommended to eliminate the following lines from your validator logic:

phoneVal = phoneVal.replace('(', '');
phoneVal = phoneVal.replace(')', '');
phoneVal = phoneVal.replace('-', '');
phoneVal = phoneVal.replace('_', '');
phoneVal = phoneVal.replace(' ', '');

Instead, utilize the unmask attribute within the p-inputMask component to maintain a clean model value:

 <p-inputMask mask="(999) 999-9999" formControlName="phone" 
   inputStyleClass="form-control"
   [unmask]="true"
   [style]="{'width': '100%','height':'34px'}" id="phoneId"
   placeholder="Phone (required)">
 </p-inputMask>

Discovery: Upon further exploration, it was found that p-inputMask does not fully support additional validators beyond the built-in required attribute. Even if a custom validator is applied, the control may still be considered valid.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Angular 2 communication between parent and child components

I am having trouble incorporating an action button in the child_1 component, while the event handler is located in the sub child component, child_2. Here's a snippet of the code: app.component.html (Parent HTML) <div style="text-align:center"> ...

When using Angular 2, the `onYouTubeIframeAPIReady` function may not be able to locate the `YT` name, even if it is defined on the

As part of my efforts to track when a user pauses a YouTube video (link to the question), I have been utilizing the onYouTubeIframeAPIReady callback method in Angular2. I am facing similar challenges as discussed here and here. Following the recommendati ...

Insert an HTML element or Angular component dynamically when a specific function is called in an Angular application

Currently, I am working on a component that contains a button connected to a function in the .ts file. My goal is to have this function add an HTML element or make it visible when the button is clicked. Specifically, I would like a dynamic <div> elem ...

Can you explain the mechanics behind the functionalities of @angular and @type dependencies?

This inquiry may have been raised before, but I couldn't uncover all the solutions. If that's the case, my apologies. I have a good grasp on how package.json and dependencies / dev-dependencies function in Node applications. Currently delving i ...

Unable to transfer data through Ionic popover

I've encountered an issue when trying to pass data to my popover component, as the data doesn't seem to be sent successfully. Code HTML <div class="message" id="conversation" *ngFor="let message of messages.notes"> <ion-row class= ...

Issue encountered with TypeORM and MySQL: Unable to delete or update a parent row due to a foreign key constraint failure

I have established an entity relationship between comments and posts with a _many-to-one_ connection. The technologies I am utilizing are typeorm and typegraphql Below is my post entity: @ObjectType() @Entity() export class Post extends BaseEntity { con ...

Develop a custom data structure by combining different key elements with diverse property values

Within my coding dilemma lies a Union of strings: type Keys = 'a' | 'b' | 'c' My desire is to craft an object type using these union keys, with the flexibility for assigned values in that type. The typical approach involves ...

Repeating the same algorithms in both the back and front ends while applying Domain Driven Design

Within my class, I have some backend calculations: public class MyDomainClass{ private Double amount; private Double total; public Double getPercentage(){ /*business logic*/ } } I am using Angular 2+ for my frontend and I am looki ...

Tips for utilizing programmatic object keys as TypeScript type?

Consider the object shown below: const obj = { foo: "bar", hello: "world", } and this function for processing objects: const process = (obj) => { const processedObj = {} for (const key in obj) { processedObj[`--${key}`] ...

AWS lambda not properly displaying static content for an Angular application when running Node Express server

Recently, I encountered an issue while trying to deploy my Angular application on AWS Lambda. I kept receiving a 403 exception for my static content, even though I used Express.js to configure the server. You can check out the problems I'm facing at t ...

I am looking to refund the sum

I need assistance with returning an amount from a specific function. I have created a function called getWalletTotalAmont() getWalletTotalAmont() { let amount = 0; this.http.post<any>(`${this.generalService.apiBaseUrl}api/wallet/getWalletTotal ...

Is it feasible to have two interfaces in Typescript that reference each other?

I am facing an issue with two interfaces, UserProfile and Interest. Here is the code for both interfaces: export default interface UserProfile { userProfileId: string, rep: number, pfpUrl: string, bio: string, experience: "beginner" | " ...

Equalizing Lists in Angular 2

Struggling to locate documentation on this topic, but in Angular 1 it was possible to achieve the following: <textarea ng-model="name" ng-list=","></textarea> With this setup, if you were to input "Hello, world!" into the textarea, the name v ...

Acquiring the download link for Firebase Storage in Angular 2+ technology

reference: AngularFireStorageReference; task: AngularFireUploadTask; uploadState: Observable<string>; uploadProgress: Observable<number>; downloadLink: Observable<string>; beginUpload(event) { const id = Math.floor(Math.random() * 1000 ...

Alter the data displayed by the Radio button using Angular when the Submit button is clicked

I've encountered an issue where I need to alter a div based on the selection of a radio button. Currently, it changes instantly upon button click, rather than waiting for submission. My desired outcome is for the value to be submitted when the button ...

Tips on integrating ActiveX controls in Angular

I built my project using Angular 6 and TypeScript in Visual Studio Code. The browser being used is IE11. Unfortunately, when I try to run the code written in app.component.html, it doesn't work as expected. The HTML code causing the issue is: <d ...

Having trouble triggering a dot MVC controller action method from an Angular service

Encountering the following Error: CORS policy block: Preflight request response access control check fails with HTTP ok status missing. Note: The ajax call successfully triggers the action method in other web applications, but an error is raised when usin ...

If you want to use the decorators plugin, make sure to include the 'decoratorsBeforeExport' option in your

Currently, I am utilizing Next.js along with TypeScript and attempting to integrate TypeORM into my project, like demonstrated below: @Entity() export class UserModel extends BaseEntity { @PrimaryGeneratedColumn('uuid') id: number } Unfortun ...

Ways to access a nested property within an array

I'm having an issue when trying to access a sub property of an array. Here's the snippet in question: ngOnInit() { this.menus = this.navService.defaultMenu; console.log(this.getMenusItem()); this.registerChangeInProjects(); } T ...

What is the best way to invoke a function that is declared within a React component in a TypeScript class?

export class abc extends React.Component<IProps, IState> { function(name: string) { console.log("I hope to invoke this function"+ name); } render() { return ( <div>Hello</div> ); } } Next, can I cal ...