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

Utilizing Angular 2 for Element Selection and Event Handling

function onLoaded() { var firstColumnBody = document.querySelector(".fix-column > .tbody"), restColumnsBody = document.querySelector(".rest-columns > .tbody"), restColumnsHead = document.querySelector(".rest-columns > .thead"); res ...

Webpack may suggest, "An extra loader might be needed" within a React.js project

I recently created a React project with two separate workspaces, named 'webmail' and 'component'. In the 'component' workspace, I added a small tsx file that I wanted to utilize in the 'webmail' workspace. Below is t ...

Issues encountered with sending post requests to a yii2 application when using Angular4

After implementing the following code: this.http.post('http://l.example/angular/create/', {name: 'test'}).subscribe( (response) => console.log(response), (error) => console.log(error) ); I encountered an error on ...

The functionality to disable the ES lint max length rule is malfunctioning

In trying to disable an eslint rule in a TypeScript file, I encountered an issue with a regular expression that exceeded 500 characters. As a result, an eslint warning was generated. To address this, I attempted to add an eslint comment before declaring th ...

Eliminate nested object properties using an attribute in JavaScript

I am working with a nested object structured like this const data = [ { id: '1', description: 'desc 1', data : [ { id: '5', description: 'desc', number :1 }, { id: '4', description: 'descip& ...

Initial values of dual knob settings on Ionic Range and their ability to update dynamically

As someone new to using Ionic and TypeScript, I am facing challenges in setting initial values for my Ionic Range component (V5). Referring to other posts, it seems that there are upper and lower properties within ngModel, but I'm unsure about the bes ...

Navigating to the Login page in Angular 13

<app-navbar></app-navbar> <div class = "app-body"> <div class="app-sidebar"> <app-sidebar></app-sidebar> </div> <div class="app-feed"> <router-outlet name="main& ...

What could be the reason behind encountering the error stating "Type 'Number' does not have any compatible call signatures"?

Hey there, I am currently working on an angular component and I have this code snippet: private approvals: Approval[] = []; ngOnInit() { this.getUsersApprovals(this.userid); } getUsersApprovals(userid) { this.approvalsService.getUsersApp ...

Utilizing a variable to pass props to a component (instead of a static component) within React Router 5

In react-router 5, you can pass props to a child component in this way: <Route path="/" exact render={ props => <MyPage title={myTitle} dataPath={myDataPath} {...props} />} /> However, I am using a route model in my ...

Displaying multiple lines in an alert box using Angular 8

I need assistance in displaying an alert message when the user selects a checkbox. We have a shared alert service component that is being utilized by every module. My current code snippet is as follows: if(this.checkboxvalue) { this.al ...

Tips for transferring ID from one Angular page to another page?

I'm wondering if there is a way to pass the id from one page to another without relying on Routing or local storage. Storing it in the service file causes it to collapse upon page refresh, so I am looking for alternative solutions. Any suggestions wou ...

Customizing output paths for script files in angular.json with Angular

Is there a way to set up the configuration in angular.json so that script files are output as shown in the directory tree below? Note: The file aaa.js has been renamed from main.js /assets/js/aaa.js ...

Working with TypeScript: Overriding a Parent Constructor

I am new to TypeScript and currently learning about Classes. I have a question regarding extending parent classes: When we use the extends keyword to inherit from a parent class, we are required to call the super() method in the child class constructor. H ...

Scrolling through a list in Angular using cdk-virtual-scroll-viewport while selecting items via keyboard input

Looking to implement a customized Autocomplete feature. As the user begins typing, a small window should appear with selectable options. I want users to have the ability to navigate and select an option using their keyboard. For instance: - User types "H ...

"Exploring the methods to retrieve Firebase authentication error details and outputting the console log message along with

When I encounter an error in Firebase authentication, I want to display it in the console log. However, nothing is being logged and the catch block is not even getting executed. I am unsure about why this is happening and how to retrieve the error code and ...

Establish a connection between a variable and the selected value of Mat-select using a form

Within my TypeScript code, there exists a variable named type whose value is provided by its parent component. This type value is essentially a string that has the possibility of being empty upon being received from the parent component. Additionally, in t ...

Unable to access due to CORS restriction on Express server

Whenever I attempt to send a POST api request to my express server, I encounter the following error message. Access to XMLHttpRequest at 'localhost:8081/application' from origin 'localhost:8083' has been blocked by CORS policy: No &apos ...

The patchValue() function in FormGroup does not fire the input event

In my code, I have a FormGroup dedicated to credit card inputs. To format the inputs, I'm using a directive with the selector 'appCreditCardFormat'. Here's a simplified version: <input formControlName="cardNo" appC ...

After the assignment, TypeScript reordered the elements of the array

Dealing with an array of objects for use in a ngFor loop has presented a challenge. The issue arises when the order that was initially set for the array changes unexpectedly due to JavaScript manipulation. Originally, the array is ordered as expected when ...

Error: An unexpected token < was caught in the TypeScript Express code

Using TypeScript to compile and run an Express server that simply serves an HTML file. However, encountering an error in the response under the network tab in Chrome for app.js: Uncaught SyntaxError: Unexpected token '<' Below is the server c ...