Angular 5 - Issue with Conditional Validator Functionality Being Ineffective

If the email field is not left empty, then the re-email field must be marked as 'required'. In order to achieve this functionality, I have implemented conditional validators for the re-email field using the code snippet below:

HTML

<div class="row">         
    <div class="form-group col-xs-6">
        <label class="control-label">Email Address:</label>
        <input type="text" class="form-control" (blur)="reEnterEmail()" [ngClass]="{ 'quote-has-error' : startPageForm.controls['email'].invalid && startPageForm.controls['email'].touched}"
        formControlName="email">
        <label class="text-danger" *ngIf="startPageForm.controls['email'].hasError('pattern') && startPageForm.controls['email'].touched">Email is invalid</label>
    </div>

    <div class="form-group col-xs-6">
        <label class="control-label">Re-enter Email Address :</label>
        <input type="text" class="form-control" (blur)= "checkReEmail()" [ngClass]="{ 'quote-has-error' : startPageForm.controls['reEmail'].invalid && startPageForm.controls['reEmail'].touched}"
        formControlName="reEmail" id="reEmailId">
        <label class="text-danger" *ngIf="startPageForm.controls['reEmail'].touched && message == 'false' &&
        this.startPageForm.controls.email.value != this.startPageForm.controls.reEmail.value" >Email is invalid</label>
    </div>
</div>

Component

this.startPageForm = new FormGroup({

              firstName : new FormControl( '', [Validators.required]),
              middleName : new FormControl( '', [] ),
              lastName : new FormControl( '', [Validators.required] ),
              suffix : new FormControl( '', [] ),
              dateOfBirth : new FormControl( this.dateOfBirth, [Validators.required, DateValidator, AgeValidator] ),
              gender : new FormControl( this.genderEnumConstants[0].value, [] ),
              maritalStatus : new FormControl( this.maritalStatusEnumConstants[0].value, [] ),
              aprtUntNumber : new FormControl( '', [] ),
              address : new FormControl( '', [] ),
              city : new FormControl( '', [Validators.required] ),
              stateId : new FormControl( '', [Validators.required] ),
              zipcode : new FormControl( '', [Validators.required, Validators.maxLength(5)] ),
              isMilitaryAddress : new FormControl( false, [] ),
              mobileNo : new FormControl( '', [Validators.required] ),
              homeNo : new FormControl( '', [] ),
              email : new FormControl( '', [ Validators.pattern("^[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,4}$")] ),
              reEmail : new FormControl( '', [] ),
              notificationMethod : new FormControl( this.notificationMethodEnumConstants[0].value, [] ),
              policyTerm : new FormControl( this.policyTermEnumConstants[0].value, [] ),
              effectiveDate : new FormControl( effectiveDate, [DateValidator, MinDateValidator] ),

        });


    reEnterEmail() {

        this.startPageForm.controls['reEmail'].setValidators(this.setRequired());
    }

    setRequired() {

        if(this.startPageForm.controls.email.value != null  && this.startPageForm.controls.email.value != '') {
            return [Validators.required];
        } else {
            return [];
        }   
    }

Upon triggering the (blur)="reEnterEmail()" event on the email field, I am assigning validators to the reEmail field. However, an error message was encountered:

Uncaught ReferenceError: Validators is not defined(…)

Answer №1

I found the solution to my issue. The problem was that I forgot to call the method updateValueAndValidity(); after applying Validators to the control.

Component:

reEnterEmail() {
        let reEmailControl = this.startPageForm.get('reEmail');
        if(this.startPageForm.controls.email.value != null  && this.startPageForm.controls.email.value != '') {
            reEmailControl.setValidators([Validators.required]);
        } else {
            reEmailControl.setValidators([]);
        }
        this.startPageForm.get('reEmail').updateValueAndValidity();
}

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 ngSubmit triggers unexpectedly on occasions when it is not supposed to

Currently, I am working on developing an Ionic 3 application with Angular 2 and TypeScript. In the app, there is a form that is responsible for sending data to our server. The issue I am facing is that whenever I click on the following button: <butto ...

What is the reason behind continuously receiving the error message stating "Not all code paths return a value here"?

Can someone help me understand why I am consistently encountering this error message from typescript? PS. I am aware that in this scenario I could simply use a boolean and not create a function, but my focus here is on typescript. I keep receiving the er ...

Creating a List programatically in material-ui can be easily achieved by following these steps

I am attempting to create a contact view using the list component from Material-UI. My code is written in typescript, but I am struggling with setting up react and material-ui correctly. Any guidance would be greatly appreciated. export interface IConta ...

Where should the API call be placed in the app.component to halt the system until the response is received and injected into the body, instead of using ngOnInit?

I am currently exploring Angular and experimenting with various features. Recently, I encountered an issue that requires me to take certain actions based on the results returned by a service before the application fully loads. Currently, I am making a cal ...

Manipulating variables across various methods in TypeScript

I have a simple code snippet where two variables are defined in the Main method and I need to access them from another method. However, I am encountering an issue with 'variables are not defined', even though I specified them in the declerations ...

Obtain information from a JSON file based on a specific field in Angular

The structure of the JSON file is as follows: localjson.json { "Product" :{ "data" : [ { "itemID" : "1" , "name" : "Apple" , "qty" : "3" }, { "itemID" : "2" , "name" : "Banana" , "qty" : "10" } ] ...

Removing a loaded stylesheet in Angular 4

One of the functions in my codebase is responsible for loading a stylesheet based on the user's language choice, whether it's 'en' or 'ar': addStyleSheet(lang: string) { let headID = document.getElementsByTagName(&apo ...

I am currently facing challenges retrieving data from a post request in my Angular/Typescript frontend application connected to an ASP.NET backend

I am currently working on a web application that relies on backend processing. To communicate between my Angular(v14)/Typescript front end and an ASP.NET backend, I am sending a post request. Backend Code [HttpPost] public async Task<string> Process ...

As I iterated over the Vehicles API data, I encountered an issue while trying to access specific Vehicle information. I received an error message stating "Cannot read property 'id' of undefined

Exploring the realms of Angular, with some experience in older versions, I find myself faced with a challenge involving two APIs - "/vehicles" and "/vehicle/{id}". The process involves fetching data from "/vehicles", iterating through it to match IDs, the ...

Calculate the variance between two variables

I am facing a challenge where I have an object and the 'Hours' field is saved as a string. I am looking to convert this string into actual hours and then calculate the difference between the two variables. const groupSchedule=[ {"days":"sat" ...

Is it possible to obtain the return type of every function stored in an array?

I'm currently working with Redux and typesafe-actions, and I am trying to find a way to automatically generate types for the actions in my reducer. Specifically, I want to have code completion for each of the string literal values of the action.type p ...

Determine the conditional type based on the type of another variable

function updateFilterData( mode: 'PaymentType' | 'Origin' | 'Destination', value: string, ) { } I need to modify this function so that when mode is 'Origin' | 'Destination', the value should b ...

bespoke arguments for the super function in a subclass of Angular

I am attempting to incorporate the ol sidebar from umbe1987/Turbo87 into an Angular project. As I extend a class, I find myself needing to manipulate constructor parameters in the derived class constructor before passing them to the superclass constructor ...

Combining array elements into functions with RxJS observables

I am facing a scenario where I have an array of values that need to be processed sequentially using observables in RxJS. Is there a more optimized way to achieve this instead of using nested subscriptions? let num = 0; let myObs = new Observable(obs ...

Combine the array elements by date in Angular, ensuring no duplicates are present

How can array data be merged based on the date while avoiding duplicates? See the code snippet below: [ { date: [ '2019-12-02 08:00:00', '2019-12-03 08:00:00' ], upload:["47.93", "47.46", "47.40", "47.29" ], download: ["43.90", ...

What is the best method to retrieve HTTP headers from the backend and simultaneously send HTTP parameters to it in ASP.NET Core and Angular?

I am currently working with Angular 15 and ASP.NET Core 5. The backend retrieves paged items based on the parameters pageSize and pageIndex. Once the action method receives the pageSize and pageIndex parameters, it sends both the paged items and the total ...

Validate prop must consist of one of two functional components

I am looking to ensure that a prop can only be one of two different components. Here is what I currently have: MyComponent.propTypes { propA: PropTypes.oneOfType([ PropTypes.instanceOf(ClassComponentA) PropTypes.instanceOf(ClassCompon ...

The module does not contain 'toPromise' as an exported member in rxjs version 5.5.2

Encountering an error when using toPromise Prior method: import 'rxjs/add/operator/toPromise'; Updated approach: import { toPromise } from 'rxjs/operators'; The new way is causing the following issues: [ts] Module '"d:/.../ ...

Managing a Angular HTTP Request on a Bottle Server where CORS is restricted

I am encountering an issue while trying to send data from my Angular 9 App to a bottle backend server. When running the application on the client side, I receive a CORS (Cross-Origin Resource Sharing) error indicating that the 'Access-Control-Allow-Or ...

Implementing conditional data binding in Angular with ngIf directive

I've been struggling to showcase recipes from a specific food category. I'm attempting to iterate through an array of recipes within a parent component. <div class="row"> <div class="col-xs-8" *ngIf="{{ recipe.category }} === mexican" ...