Issues with multiple validators in Angular 8 intricately intertwined

I'm facing an issue with a reactive form control that has multiple validators. Despite defining the validation methods, the form is not being validated as expected. Below is the code snippet illustrating my attempted solutions.

Method 1:

civilIdNumber: new FormControl("", Validators.compose([Validators.required, Validators.minLength(12), Validators.maxLength(12), Validators.pattern("^[0-9]*$")])),

Method 2:

civilIdNumber: new FormControl("", [Validators.required, Validators.minLength(12), Validators.maxLength(12), Validators.pattern("^[0-9]*$")])

HTML Code:

<form [formGroup]="customerForm">
    <div class="col-sm-6">
              <div class="form-group">
                <label for="civil">Civil ID Number</label>
                <input
                  type="number"
                  placeholder="Civil ID Number"
                  class="form-control"
                  id="civil"
                  formControlName="civilIdNumber"
                  required
                  [ngClass]="{ 'is-invalid': customerForm.controls.civilIdNumber.invalid && customerForm.controls.civilIdNumber.touched }"
                />

                <div *ngIf="customerForm.controls['civilIdNumber'].invalid && (customerForm.controls['civilIdNumber'].dirty || customerForm.controls['civilIdNumber'].touched)" class="text-danger">
                  <div *ngIf="customerForm.controls['civilIdNumber'].errors.required">Civil ID Number required</div>
                </div>
              </div>
     </div> 
</form>

Answer №1

Within your TypeScript file

customerForm: FormGroup;
constructor(formBuilder: FormBuilder) {
this.customerForm = this.formBuilder.group(
   {
    civilIdNumber: ["", [Validators.required, Validators.minLength(12), 
    Validators.maxLength(12), Validators.pattern("^[0-9]*$")] ]
   }
)
}

In your HTML template

<div class="col-sm-6" [formGroup]="customerForm"> <!-- ensure this line is included for functionality -->
          <div class="form-group">
            <label for="civil">Civil ID Number</label>
            <input
              type="number"
              placeholder="Civil ID Number"
              class="form-control"
              id="civil"
              formControlName="civilIdNumber"
              required
              [ngClass]="{ 'is-invalid': customerForm.get('civilIdNumber').invalid && customerForm.get('civilIdNumber').touched }"
            />

            <div *ngIf="customerForm.get('civilIdNumber').invalid && (customerForm.get('civilIdNumber').dirty || customerForm.get('civilIdNumber').touched)" class="text-danger">
              <div *ngIf="customerForm.get('civilIdNumber').errors.required">Civil ID Number is required</div>
            </div>
          </div>
</div>

Answer №2

Your control is not properly bound. The form control name only makes sense within the context of its parent formGroup (or formArray, but let's skip that for now)

<div class="col-sm-6" [formGroup]="customerForm"> <!-- this is the key to making it work -->
          <div class="form-group">
            <label for="civil">Civil ID Number</label>
            <input
              type="number"
              placeholder="Civil ID Number"
              class="form-control"
              id="civil"
              formControlName="civilIdNumber"
              required
              [ngClass]="{ 'is-invalid': customerForm.controls.civilIdNumber.invalid && customerForm.controls.civilIdNumber.touched }"
            />

            <div *ngIf="customerForm.controls['civilIdNumber'].invalid && (customerForm.controls['civilIdNumber'].dirty || customerForm.controls['civilIdNumber'].touched)" class="text-danger">
              <div *ngIf="customerForm.controls['civilIdNumber'].errors.required">Civil ID Number is required</div>
            </div>
          </div>
</div>

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

Execute a grandchild function in Angular that triggers its grandparent function

I'm currently working with a component structure that looks like this: Component A -> Component B -> Component C Within the template of Component C, there is a button that triggers a function in the 'code behind' when clicked. My go ...

Encountering issues with Google authentication functionality while using AngularFire2

Currently in the process of setting up Google Authentication with Firebase and AngularFire2. The setup seems to be partially functional, however, there are some unusual behaviors that I am encountering. Upon the initial loading of the app, the Login button ...

The display of buttons in Ag-Grid Cell Render is not appearing correctly when integrated with Angular Material tab component

Recently, I integrated ag-grid into one of my projects and successfully created a Cell Renderer to showcase buttons in the "actions" columns. However, when I transferred the grid into an Angular material, I noticed a peculiar issue. Upon navigating to the ...

Getting the button element in Angular when submitting a form

My web page contains multiple forms, each with a set of buttons. I want to incorporate a loading spinner on buttons after they are clicked. When using a regular click event, I am able to pass the button element: HTML <button #cancelButton class="butto ...

Mismatch between TypeScript library and Angular web application: certain properties are absent

I am currently facing a dilemma with my two angular projects. The first one is a library while the second one is a regular Angular webapp. Within my library project, I have the following code snippet: class User { firstName: string; lastName: stri ...

The argument of type 'NextRouter' cannot be assigned to the parameter of type 'Props' in this scenario

In my component, I am initializing a Formik form by calling a function and passing the next/router object. This is how it looks: export default function Reset() { const router = useRouter(); const formik = useFormik(RecoverForm(router)); return ( ...

Angular and Bootstrap are like peanut butter and jelly -

Recently, I've been delving into Angular and attempting to integrate Bootstrap into my projects. To install Bootstrap using npm, I ran the following command: cmd npm install bootstrap --save After the installation, I imported the necessary styles in ...

"Angular 6: A Guide to Customizing Text Colors Based on Status

I have a view on angular just like this: https://i.sstatic.net/JimWN.png And this is my dashboard.component.ts: export class DashboardComponent implements OnInit { tablePresetColumns; tablePresetData; ngOnInit() { this.tablePresetColumns = [{id: ...

What is the best way to adjust the size of an HTML5 SVG circle with a button click event?

If you click the button, the text size will increase or decrease. <div class="buttons"> <button (click)="fSize = fSize + 1">+</button> <button (click)="fSize = fSize - 1">-</button> </div> <br> <div [ ...

Toggle the visibility of the navigation bar in Angular based on the user

I have implemented rxjs BehaviorSubject in my login page to transmit data to auth.service.ts, enabling my app.component to access the data stored in auth.service.ts. However, I now require the app.component to detect any changes made to the data in auth.se ...

Revise the observable to trigger a NgbModal from a service

I have a situation in my Angular 11 service where I am using a Ngbmodal component to subscribe when it is closed. Below is the code snippet: showMessage(messageData: MessageDataDTO): Observable<MessageResult> { return new Observable((result) =&g ...

What is causing my auth0 token to expire upon refreshing the page or clicking a link in my Angular application?

I've implemented authentication in my Angular single-page application using auth0. I followed a tutorial on their website: https://auth0.com/docs/quickstart/spa/angular2 After completing the login tutorial, everything seemed to be working fine. impo ...

Unlocking the power of module augmentation in Typescript: Enhancing library models within your app domain

I currently work with two applications that share the same code base for their models. I am interested in developing and sharing a library model using inheritance in TypeScript. For instance, Pet extends Author. In my current Angular application, I need ...

Create a tuple type by mapping an object with generics

I have a specified object: config: { someKey: someString } My goal is to generate a tuple type based on that configuration. Here is an example: function createRouter< T extends Record<string, string> >(config: T) { type Router = { // ...

The function named updateContact is not defined, even though it has been declared

Presented below is Angular code snippet: @Component({ selector: 'app-detail-view', templateUrl: './detail-view.component.html', styleUrls: ['./detail-view.component.css'] }) export class DetailViewComponent implements O ...

Exploring the archives of PubNub within Angular5

I've been working on integrating PubNub history into my web app, but I'm currently only able to view it in the console. Here's what I have so far: pubnub.history( { channel: 'jChannel', reverse: false, ...

Node-express can seamlessly switch between multiple databases dynamically

After extensive searching for a solution to my problem, I have come up empty-handed. If anyone has experience in similar situations, your help would be greatly appreciated. I have developed an application server in Node Express with MySQL as the database. ...

What is the process for integrating an extension function into an Express response using TypeScript?

I am looking to enhance the Response object in Express by adding custom functions. Specifically, I want to introduce a function: sendError(statusCode: number, errorMessage: string) which can be called from anywhere like this: response.sendError(500, &qu ...

Issue with Moment.js: inability to append hours and minutes to a designated time

I have a starting time and I need to add an ending time to it. For example: start=19:09 end=00:51 // 0 hours and 51 minutes I want to add the 51 minutes to the 19:09 to make it 20:00. I've attempted several different methods as shown below, but none ...

Organizing a collection of bags using ng2-dragula technology

I have successfully implemented ng2-dragula for a dynamic sorting user interface. Currently, I can reorder the <li> elements within each container. <div *ngFor="let bag of chest" class='container'> <ul [dragula]='"bag-one"& ...