Implementing dynamic validation rules in Angular forms

In my code, there is a part where I need to make certain fields required. Initially, only the emailAddress field is required, but under a specific condition (res.isSuccess === true), I also need to set firstName, lastName, and companyName as required.

The issue I'm facing is that the mat error message is already displayed upon the initial load, which should not happen. It should only appear when a field like the firstName is touched or clicked.

Any thoughts on how to resolve this problem? Thank you.

#html

 <mat-form-field class="full-width" appearance="fill" style="margin-top: 26px;">
    <mat-label>First Name *</mat-label>
    <input matInput formControlName="firstName">
    <mat-error
        *ngIf="modelForm.get('firstName').hasError('required')  && (modelForm.get('firstName').touched || modelForm.get('firstName').dirty)">
        First Name is required.
    </mat-error>
</mat-form-field>

getStarted() {
    this.AccountRoleDetails = null;
    if (this.userService) {
        this.userService
            .getUserEmail(this.accountId, this.modelForm.value['emailAddress'])
            .subscribe(
                (res: any) => {
                    if (res.isSuccess === true) {
                        this.setRequiredValidations();
                    }
                });

.........

#Code

initFormGroup() {
    this.modelForm = this.formBuilder.group({
        id: [this.model.id || 0],
        emailAddress: [this.model.emailAddress, Validators.required],
        firstName: this.model.firstName,
        roleId: this.model.roleId,
        lastName: this.model.lastName,
        phoneNumber: this.model.phoneNumber,
        companyName: this.model.companyName,
    });
}

#code 2

setRequiredValidations() {
    this.modelForm.get('firstName').setValidators(Validators.required);
    this.modelForm.get('lastName').setValidators(Validators.required);
    this.modelForm.get('companyName').setValidators(Validators.required);

    this.modelForm.updateValueAndValidity();
}

https://i.sstatic.net/v4Lyc.png

Answer â„–1

Consider removing

this.modelForm.updateValueAndValidity();

It's possible that this code is causing the Angular Reactive forms to validate the value, which may result in it being invalid if it's empty and marked as "required".

For your mat-error HTML tag, try organizing the logic more clearly:

<mat-error *ngIf="(modelForm.get('firstName').hasError('required') && 
    modelForm.get('firstName').touched) || 
    modelForm.get('firstName').dirty">
        First Name is required.
</mat-error>

You could also consider adjusting the logic like this:

<mat-error *ngIf="modelForm.controls.firstName.invalid &&
                  modelForm.controls.firstName.dirty">
        First Name is required.
</mat-error>

Or:

<mat-error *ngIf="modelForm.controls.firstName.invalid &&
                  modelForm.controls.firstName.touched">
        First Name is required.
</mat-error>

Depending on your specific UI/UX needs.

This will help in identifying why the status is showing as invalid. You can use the browser console for inspection.

Also, make use of browser tools to view form field validation errors, values, and validity status before and after setting new validators. Accessing the "required" status might need a different approach.

Could you share the values obtained from the browser console and update your question?

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

What is the best way to increase a JSON value in a Typescript scenario? For instance, how can I add more

Is there a way to update JSON values in a TypeScript example by incrementing likes or dislikes when a button is clicked?https://i.sstatic.net/aon03.png movies: any[] = [ { name: "Fan", likes: 0, dislikes: 0, unseen: 0, fimage: "/images/fan.jpg" }, ...

Tips for solving the error "Angular CLI version 7.0.3 cannot install node-sass"

Every time I attempt to run npm start, an error message stating that it cannot find the module node-sass appears. Then, when I try running npm install node-sass --save, a series of errors pop up. https://i.stack.imgur.com/2I7DU.png ...

When invoking a callback function that includes a conditional type, TypeScript mandates the inclusion of a parameter that intersects multiple types

There is a function that requires specific arguments, including a callback function that takes an object or an array of objects based on an isArray parameter. I am attempting to create a new feature. type Option = { name: string value: string } type ...

Is it possible to reference the prior value of a computed Angular signal in any way?

Is it possible to dynamically add new values from signal A to the existing values in signal B, similar to how the scan operator works in RxJS? I am looking for something along the lines of signalB = computed((value) => [...value, signalA()]). Any sugg ...

Angular8 is displeased with the unexpected appearance of only one argument when it was clearly expecting two

Even though I have declared all my requirements statically in my component.html file, why am I receiving an error stating "Expected 2 arguments but got 1"? I use static concepts, so it's confusing to encounter this type of error. Below you can see th ...

Deleting a specific row from a material table mat-table

Can anyone provide guidance on how to remove a selected row in mat-table using Angular? Please refer to the Stackblitz link provided below. https://stackblitz.com/edit/angular-qzh8g4?file=app/table-basic-example.ts I attempted to implement a solution, but ...

The input feature in the Angular 4 Library allows users to easily

Hello everyone, I could really use some assistance with a problem I am facing. For some reason, I can't seem to make it work properly. I suspect that there might be an issue with the syntax I am using. Currently, I am in the process of developing Ang ...

The output from Angular Validator.pattern() may differ from that generated by online regex engines

Currently, I am facing an issue with my form group and a regular expression used to validate names. The criteria for the name input field are: It must be required. It should be alphanumeric. It must start with alphabets. It cannot contain any special char ...

Angular2 - trigger an HTTP GET request from a different component

At my workplace, I mainly use AngularJS (1.5) but recently ventured into creating my first Angular2 application. However, I've encountered a slight issue with observables. The service I'm working with is the TicketService: import { Injectable, ...

The conversion to ObjectId was unsuccessful for the user ID

I'm looking to develop a feature where every time a user creates a new thread post, it will be linked to the User model by adding the newly created thread's ID to the threads array of the user. However, I'm running into an issue when trying ...

What could be causing the Google Sign-In functionality to fail in an Angular web application?

I'm currently working on implementing Google sign-in for my web app. I've been following this tutorial here. However, I'm facing an issue where the Google sign-in button is not appearing. I would like the authentication to happen at http://l ...

Switch over tslint to @angular-eslint/schematics: Cannot resolve dependency tree: @angular/[email protected] due to ERESOLVE

I am in the process of transitioning from tslint to eslint in my Angular 11 library by following the official documentation here. After running the command ng add @angular-eslint/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail=" ...

The utilization of the Angular date pipe significantly impacts the way dates are

When I use the pipe date:'MM/dd/YYYY' to display the date 2022-01-01T00:00:00, it shows as 1/01/2021 instead of 1/01/2022. This issue only occurs with this specific date. Why does this happen? The value of pharmacyRestrictionDate is 2022-01-01T0 ...

Utilizing the dialogue feature within Angular 6

Situation: I am managing two sets of data in JSON format named customers and workers: customers: [ { "cusId": "01", "customerName": "Customer One", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data- ...

`Inconsistencies in console.log output with Angular Firestore``

I'm currently working on retrieving the id of selected data, but when I test it using console.log, it keeps outputting twice. The image below illustrates the console.log output. https://i.stack.imgur.com/IARng.png My goal is to fetch the id once and ...

Having trouble uploading an image using Angular, encountering an error in the process

Whenever I try to upload an image, the server keeps throwing an error saying Cannot read property 'buffer' of undefined. I am using Node.js as a backend server and interestingly, when I send the image through Postman, it gets stored in MongoDB wi ...

Utilizing the map function in Angular while disregarding any null values

I have an array of objects in my dataset. Here's a glimpse of how it is structured: [ { "id": 1, "name": "john", "address": { "number": 42, "street": "High Street"} }, { ...

Does moment/moment-timezone have a feature that allows for the conversion of a timezone name into a more easily comprehendible format?

Consider this example project where a timezone name needs to be converted to a more readable format. For instance: input: America/Los_Angeles output: America Los Angeles While "America/Los_Angeles" may seem human-readable, the requirement is to convert ...

Angular Bootstrap Modal not Displaying

<img id="1" data-toggle="modal" data-target="#myModal" data-dismiss="modal" src='assets/barrel.jpg' alt='Text dollar code part one.' /> <div id="myModal" class="modal fade" *ngIf="isModalShowing"> <div class=" modal-lg ...

When dealing with errors arising from API calls, Angular can be prone to throwing error messages

I am currently creating an Angular service class to interact with APIs. However, I am facing an issue when handling Internal server errors in the response and need to send an error message to the user. The services are designed for retrieval but encounteri ...