Validating a field conditionally upon submission

Adding a required validation conditionally to the "imageString" field upon submission, but the expected required validation is not being set.

Initializing the form.

constructor(){
 this.poeForm = this.fb.group({
      imageString: [""],
      imageFileName: [""],
    }
 }
}

Upon saving, the validation for the imageString field is invoked.

   saveForm() {
       this.profileImgValidator();
       this.getFormValidationErrors();
       if (this.poeForm.invalid) {
          Swal.fire("Please fill in all the required fields");
          return;
        }
      }

The actual logic for setting the value.

 profileImgValidator(){
    let errors = null;
    this.mandatoryFields = //server call it will return value or null
    if(this.mandatoryFields){     
        this.poeForm.get('imageString').setValidators(Validators.required);
      }else{
        this.poeForm.get('imageString').clearValidators();
      }    
    return errors;
  }

Checking by iterating through form controls.

 getFormValidationErrors() {
    Object.keys(this.poeForm.controls).forEach(key => {
    const controlErrors: ValidationErrors = this.poeForm.get(key).errors;
    if (controlErrors != null) {
          Object.keys(controlErrors).forEach(keyError => {
            console.log('Key control: ' + key + ', keyError: ' + keyError + ', err value: ', controlErrors[keyError]);
          });
        }
      });
    }

Answer №1

Utilizing Angular's Reactive Form with custom validators can greatly enhance your form validation process. Check out the custom validators documentation for more information.

this.myForm = this.fb.group({
  email: [''],
  password: ['']
 }, { validators: customValidator } // implement custom validator
}

export const customValidator: ValidatorFn = (control: FormGroup): ValidationErrors | null => {
 const email = control.get('email').value;

 if (this.requiredField) {
   return email ? null : { required: true }
 }

 return null;
};

Answer №2

Check out the code snippet below:

validateProfileImage() {
  let errors = null;
  this.requiredFields = //make a call to the server to get data
  
  const imageItem = this.profileForm.get('image');
  if (this.requiredFields) {
    imageItem.clearValidators();
    imageItem.setValidators(Validators.required);
  } else {
    imageItem.clearValidators();
  }

  imageItem.updateValueAndValidity();
  this.profileForm.updateValueAndValidity();

  return errors;
}

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

Is it possible to update duplicated records in Firestore using a cloud function when there are changes made to the document

In my Firestore setup, I have the following structure: Users / uid / following / followingPersonUid / Users / uid / followers / followerPersonUid / When User A follows User B, User A is added to the followers sub-collection of User B and User B is added ...

Running PHP scripts within an Angular2 CLI application

I'm currently working on an Angular 2 app using Angular CLI, but I've noticed that the PHP files are not being compiled correctly. I'm curious if the server that is included with Angular CLI supports PHP. If not, do you have any recommendati ...

Ways to show a div when a dropdown option is selected

Currently, I am in the process of designing a form that includes a dropdown menu. Once the user selects a particular option from the list, such as: Software developer a new section will be displayed, showing two additional options: App Developer ...

Exploring Several Images and Videos in Angular

I'm experiencing a challenge with displaying multiple images and videos in my Angular application. To differentiate between the two types of files, I use the "format" variable. Check out Stackblitz export class AppComponent { urls; format; on ...

Guide to adding information to a table with the help of an "interface" in Angular 6 and utilizing Typescript

Looking for some guidance with Angular as I am just starting out. I am currently trying to send an API request in angular 6 using Typescript. However, I am facing difficulties when it comes to adding data to a table. Check out my code on: Codepen In my p ...

Passing a click event to a reusable component in Angular 2 for enhanced functionality

I am currently working on abstracting out a table that is used by several components. While most of my dynamic table population needs have been met, I am facing a challenge with making the rows clickable in one instance of the table. Previously, I simply ...

Encoding and Decoding Base64 in Nativescript Using Angular 2

I've searched high and low for a solution but I can't seem to find one. Even after attempting to utilize atob() and btoa(), my efforts were futile. It seems that despite what intellisense suggests, these methods cannot be used. Additionally, plug ...

Extracting arrays from JSON in Angular: A step-by-step guide

I am currently working with Angular2 (version 5) and facing an issue. I am able to make an HTTP request and receive JSON data. While I know how to access and use individual values, I am struggling with accessing and extracting the two arrays inside an elem ...

What is the best way to export an Angular application for users who do not have access to npm

Currently, I am developing an Angular application for a school assignment. The project is complete and runs smoothly on the console. Unfortunately, our instructors lack the patience and IT expertise to install NPM and run the project via the console. Is ...

Using Rxjs for MongoDB Document References: A Step-by-Step Guide

Currently, I am working on an app using Ionic2/rc0. In my singleton service, I have a ReplaySubject that maintains the consistency of the current user throughout the entire application. Everything is functioning properly, and I can easily subscribe to it a ...

Checkbox with an indeterminate state in Angular

I'm currently working on updating an AngularJS (1.5) setup where a parent checkbox becomes indeterminate if one of its children is selected, and all the children are selected if the parent is selected. My main challenge lies in converting the old ES5 ...

I am unable to employ filtering in TypeScript

Hey there, I'm trying to filter some JSON data randomly by using this function, but I keep running into an error with my variable called filteredArray. The error message says "Property 'filter' does not exist on type 'Dispatch<SetSta ...

The module ~/assets/images/flags/undefined.png could not be found in the directory

When I use the img tag with a dynamic address filled using require, it works well in the component. However, when I try to write a test for it, an error is thrown. console.error Error: Configuration error: Could not locate module ~/assets/ima ...

Looking to merge two components into one single form using Angular?

I am currently developing an Angular application with a dynamic form feature. The data for the dynamic form is loaded through JSON, which is divided into two parts: part 1 and part 2. // JSON Data Part 1 jsonDataPart1: any = [ { "e ...

How to retrieve an array stored within a JSON object

I am trying to access a specific array within an object from a JSON file. Here is the snippet of the data I'm dealing with: best-sellers": [ { "title": "Chuteira Nike HyperVenomX Proximo II Society", "price": 499.90, "installmen ...

What could be the reason for my provider loading the data twice?

Recently, I have been following a tutorial on building an Ionic app that displays information about National Parks. The data is stored locally and loaded by a Provider in my application. However, I noticed that the data is being loaded twice by the Provide ...

The modal feature on ng-bootstrap.github.io is failing to function properly when used with the Bootstrap3 CSS

Struggling to understand why the modal displays when using Bootstrap 4 with ng-bootstrap, but not displaying with Bootstrap 3. ...

Acquire the Angular Type<> directly from the component instance in Angular 5

First and foremost, I want to clarify that my requirement is for the Angular Type instance of a component, not just the TypeScript definition. The current scenario is as follows: I am working within a service where I receive an input of the actual instanc ...

Prevent selection of past dates and times in ng-bootstrap calendar in Angular 7

HTML <ngb-datepicker (select)="onDateSelect($event)" [(ngModel)]="datePickerModel"></ngb-datepicker> <ngb-timepicker [meridian]="meridian" [(ngModel)]="time" class="fromTimePick"> </ngb-timepicker> Is it possible to restrict the ...

Upgrading host and ComponentResolver from AngularDart version 4 to version 5

I'm currently in the process of transitioning a large Angular4 application (recently upgraded from Angular2) to Angular5. Within various sections of the application, we employ a directive to mark a div or other html element for generation inside that ...