Angular - Implementing validation for maximum character length in ngx-intl-tel-input

Utilizing the ngx-intl-tel-input package in my Angular-12 project multistep has been quite promising. Below is a snippet of the code:

Component:

import {
  SearchCountryField,
  CountryISO,
  PhoneNumberFormat
} from 'ngx-intl-tel-input';

export class SignupCompanyComponent implements OnInit {
  // Component logic here
}

HTML:

<mat-horizontal-stepper [linear]="isLinear" #stepper labelPosition="bottom">
  <mat-step [stepControl]="companyForm">
    // HTML template for company form
  </mat-step>
  <mat-step [stepControl]="idForm">
    // HTML template for ID form
  </mat-step>
</mat-horizontal-stepper>

While inputting data, certain issues have arisen with the mobileNumber field in ngx-intl-tel-input:

  1. The users are able to exceed the specified 15-character maxlength.

  2. When the character count exceeds 15, the Next button gets disabled without any error indication, leading to user confusion.

I am seeking guidance on resolving these issues effectively. Any assistance would be greatly appreciated.

Thank you!

Answer №1

It appears that the ngx-mat-intl-tel-input library does not support maxLength validation.

Instead, you'll need to utilize validatePhoneNumber to check if the entered text is a valid phone number. The official documentation (Example section) offers this guidance:

To display a sample number for the chosen country or errors, use mat-hint and mat-error as shown below:

<mat-error *ngIf="f.form.controls['phone']?.errors?.validatePhoneNumber">Invalid Number</mat-error>

If the Next button remains disabled, it may be because the entered phone number does not meet the required format for the selected country.


SOLUTION

The HTML for validating validatePhoneNumber should look like this:

signup-company.component.html

<div *ngIf="fc.mobileNumber.touched && fc.mobileNumber.invalid">
  ...
  <div *ngIf="fc.mobileNumber.hasError('validatePhoneNumber')">
    <div class="text-danger">
      Invalid Phone Number!
    </div>
  </div>
</div>

Don't forget to remove Validators.maxLength(100) from the mobileNumber field since it is no longer necessary.

signup-company.component.ts

this.companyForm = this.fb.group(
{
  companyName: [
  '',
  [
    Validators.required,
    Validators.minLength(3),
    Validators.maxLength(100)
  ]],
  mobileNumber: ['', [
    Validators.required
  ]]
},
{
  updateOn: 'blur'
});

See a sample solution on StackBlitz

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

The issue with ngModel in Angular is that it fails to update the value within the component

My ngModel doesn't seem to be functioning properly when I use it with a textbox in my application. This is the code snippet from app.component.html: <input type="text" [value]="name" [ngModel]="name"> Name is: {{na ...

The object literal is restricted to defining existing properties, and 'id' is not a recognized property in the type 'FindOptionsWhere<Teacher>'

I encountered a persistent error within my teachers.service: Object literal may only specify known properties, and 'id' does not exist in type 'FindOptionsWhere | FindOptionsWhere[]'.ts(2353) FindOneOptions.d.ts(23, 5): The expected t ...

Transforming class attributes in Typescript

I am facing a situation where I need to alter the type of a variable that stores an object based on certain conditions. Here is the variable in question: class MyClass { public referrers: SelectItemGroup[]; } The issue arises when I only need to add a ...

Unforeseen results arise when using the ng-if directive on a DIV element within an Angular context

@angular/upgrade/static Attempting to upgrade an AngularJS controller to Angular context using UpgradeModule from '@angular/upgrade/static' Encountering issues when changing ng-show to ng-if on span or div elements, as the enclosed content does ...

The Observable pipeline is typically void until it undergoes a series of refreshing actions

The issue with the observable$ | async; else loading; let x condition usually leads to staying in the loading state, and it requires multiple refreshes in the browser for the data to become visible. Below is the code snippet that I utilized: // TypeScript ...

Material UI is not capable of utilizing Props

I'm having trouble using the Checkbox component from Material UI. Even though I can't seem to use the normal props like defaultChecked or size="small", as it gives me the error TS2769: No overload matches this call. TS2769: No overload ...

Angular version 4.X.X: Utilizing keyValueDiffer in your code

Looking for guidance on properly utilizing the keyValueDiffer in the latest Angular versions. I'm running into an issue where the create() method is deprecated due to changes in ChangeDetectorRef. this.diff = this.keyValueDiffer.find(obj).create(null ...

Unable to set up ng-bootstap on Angular version 16.1.3

Upon attempting to integrate ng-bootstrap with Angular 16.1.3, an error was encountered during installation: Would you like to proceed? Yes npm ERR! code ERESOLVE npm ERR! ERESOLVE could not resolve npm ERR! npm ERR! While resolving: <a href="/cdn-cgi/l ...

Dependency type ContextElementDependency does not have a module factory available

As I make changes to the structure of my Angular 4 app with lazy loaded modules, I am encountering an error when running: ng build The error message displayed is: Error: No module factory available for dependency type: ContextElementDependency This e ...

Whoops! Looks like there was a hiccup with the Vercel Deployment Edge Function, causing an

Every time I attempt to send a POST request to my Edge Function on Vercel Deployment, I encounter the following error message: [POST] /api/openai reason=EDGE_FUNCTION_INVOCATION_FAILED, status=500, user_error=true TypeError: Illegal invocation at app/api/ ...

Angular 2 form with ng2-bootstrap modal component reset functionality

I have implemented ng2-bs3-modal in my Angular 2 application. I am now looking for a way to clear all form fields when the close button is clicked. Can anyone suggest the best and easiest way to achieve this? html <button type="button" class="btn-u ...

The variable 'form' has not been assigned an initial value in the constructor of the property

Below is the snippet from my component.ts file: import { Component, OnInit } from '@angular/core'; import { Validators, FormControl, FormGroup, FormBuilder } from '@angular/forms'; @Component({ selector: 'app-license', te ...

Issue encountered during mozjpeg installation - unable to locate mozjpeg's cjpeg in the vendor directory due to

During my attempt to set up mozjpeg within a Docker container running NAME="Alpine Linux" ID=alpine VERSION_ID=3.11.7 PRETTY_NAME="Alpine Linux v3.11" HOME_URL="https://alpinelinux.org/" BUG_REPORT_URL="https://bugs.alpin ...

When calling undefined typescript, the async function does not return a value but displays its result afterwards

When I debug my function, it waits until the return statement, but when I call the function, it returns undefined and the errors are also undefined. I'm not sure why this is happening. import userModel from '../Models/user.model'; const bcr ...

Looking for assistance with transforming my Angular 2 component into an npm package

After successfully creating a component in Angular 2, my next step is to convert it into an npm library for easy installation. npm install Despite installing Angular CLI and searching online, I have been unable to find clear instructions on how to effe ...

Angular - Implementing filter functionality for an array of objects based on multiple dropdown selections

I am currently working on filtering an array of objects based on four fields from a form. These four fields can be combined for more specific filtering. The four fields consist of two dropdowns with multiple selection options and two text boxes. Upon cli ...

What is the best way to convert one array of types to another array of types in Typescript?

Imagine you have the following: type AwesomeTuple = [string, number, boolean] Now, you're looking to transform that type using a generic approach: type AmazingGeneric<T extends any[]> = ... In this scenario: AmazingGeneric<AwesomeType> w ...

Storing information from JSON into an object

I am encountering an issue regarding transferring data from JSON to an object. Although this solution is functional, it is not entirely satisfactory. Take a look at the service. Is there an improved method for handling data conversion from this JSON to an ...

How can you effectively blend Vue/Angular with other JavaScript resources to enhance your development process?

My curiosity lies in understanding how front-end javascript libraries such as Vue and Angular can seamlessly integrate with other libraries and assets. For instance, if I were to procure a website template already equipped with additional javascript, is it ...

The Angular language service is experiencing difficulties in VS Code when it comes to newly created components using the CLI

I am currently facing an issue with the angular language service in an older project that already has a few components created. The problem arises when trying to generate NEW components using the CLI. For instance, a new component generated today: https:/ ...