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

Trouble encountered during installation of Angular CLI: module.js - code 549

I recently encountered issues with Angular-CLI, so I decided to update it using the command $ npm install -g @angular/cli. However, after doing so, I am facing a new error message. Can anyone provide assistance with this problem? module.js:549 throw err ...

The challenge with the Optional Chaining operator in Typescript 3.7@beta

When attempting to utilize the Typescript optional chaining operator, I encountered the following exception: index.ts:6:1 - error TS2779: The left-hand side of an assignment expression may not be an optional property access. Here is my sample code: const ...

Display the HTML string as regular text in an Angular application

I'm working on a blog project with Angular. I need to display HTML content retrieved from the database as plain text for each blog post preview. The HTML formatting was done with ngx-quill. While I can render the rich text using <quill-view [conte ...

What is the best way to expand all parent nodes of a specific child node in Angular 8 using the nested tree control of the mat tree?

getBookOutlineBar method is designed to take a list of nodes along with the selected node that needs to be highlighted when the outline sidebar opens. However, the current implementation only expands one specific node instead of all parent nodes. For exam ...

When attempting to display an identical image on two distinct canvas elements in Angular 6

I am facing an issue where the image is only rendered on the second canvas instead of both canvases. I need assistance in finding a solution to render the same image on both canvases. Below is a screenshot demonstrating that the image is currently only re ...

What is the best way to merge multiple nested angular flattening operators together?

I am facing a challenge in utilizing the outcomes of Observables from various functions. Some of these functions must be executed sequentially, while others can run independently. Additionally, I need to pass the result of the initial function to some nest ...

The Instagram Basic Display API encounters an issue when processing a request for a user profile that does

Following the migration of our code from legacy api to basic display, we encountered an issue where no media is being retrieved for users who have not set their age in their profile. Instead, we are consistently receiving the following error: { "err ...

After installing the latest version of Node.js, the stability of the Ionic environment

After updating nodejs from v8.1 to v12, my ionic environment is experiencing instability. Any suggestions on what needs to be updated? [abc]$ ionic cordova emulate android When running ng run app:ionic-cordova-build --platform=android, an unhandled exce ...

What is the best way to combine various ngrx selectors together?

I currently have 3 selectors in my index.ts file export const selectDetails = createSelector( // some code ); export const selectTransactionResponse = createSelector( // some code ); export const selectAdditionalDetails = createSelector( // some code ); ...

What are some ways to control providers in targeted tests using ng-mocks?

I recently started utilizing ng-mocks to streamline my testing process. However, I am struggling to figure out how to modify the value of mock providers in nested describes/tests after MockBuilder/MockRender have already been defined. Specifically, my que ...

Tips for concealing error messages in Angular 7 when an input field is in focus

Is there a way to hide the custom validation message div when the input field is in focus? I'm looking for a solution to this issue. <div class="form-group"> <label class="col-sm-4 control-label">Password</label> <div class ...

npm-bundle encounters an issue with Error: ENOENT when it cannot find the file or directory specified as 'package.json'

npm-bundle is throwing an error that says Error: ENOENT: no such file or directory, open 'package.json' in my NodeJs project. It works fine if I manually create test.js and package.json, then run npm install followed by npm-bundle. However, when ...

Problem encountered during NextJS build: ReferenceError - 'window' is undefined

While I am in the process of developing my app, I have encountered a perplexing issue with a ReferenceError: window is not defined. This error seems to be happening even though I am utilizing 'use client' "use client"; import React, { u ...

Encountering an issue while constructing a JSON path in SQL using values from a column

When running the query below, I encountered an error: The second argument of "JSON_VALUE or JSON_QUERY" must be a string literal. SELECT JSON_QUERY(sr.Options, CONCAT('$[', sr.OptionId,']') FROM Survey as sr The 'Options' ...

Exploring Nested <Routes> with ReactJs

My decision on whether to display the Foo page or the Bar page is based on the route. However, the Foo page itself contains two sub-routes for components to render depending on the URL path - such as FooOne or FooTwo. This results in having two layers of r ...

Type Error TS2322: Cannot assign type 'Object[]' to type '[Object]'

I'm facing an issue with a code snippet that looks like this: export class TagCloud { tags: [Tag]; locations: [Location]; constructor() { this.tags = new Array<Tag>(); this.locations = new Array<Location>(); ...

How can I utilize the color prop in the theme file to style new variants more comprehensively with MUI theming?

I am working on creating a custom variant for an MUI button where the color specified in the color prop should be applied as both the border and text color. While the MUI documentation offers a suggested approach, it requires addressing each available col ...

What is the best way to ensure that two promises are both resolved before triggering a function from within a promise?

In my code, I have a forEach loop on a matches fetch that looks like this: matches => { matches.forEach(match => { Promise.all([this.teamService.getTeam(match._links.homeTeam.href)]) .then(team => { match. ...

Transfer the HTTP functionality to a separate service using Angular2 and TypeScript

Currently diving into learning Angular2 and TypeScript after years of using Angular 1.*. I have a top level component that has a property derived from a custom type created in another class. When ngOnInit() is triggered, it makes an HTTP call to a mock RES ...

Creating a TypeScript schema with nested maps and arrays using Dynamoose

I'm currently in the process of developing a schema for a specific example: { "foods": [ { "fruits": [{ "apple": { "color": "red", ...