Implementing Conditional Validation Triggers in Angular

My app is built using Angular 8. It features a form where users can input movie details and ticket information.

Data Model Setup:

export class Movie
{
  name:string;
}

export class Ticket
{
   name:string;
   price:number;
}

To create the form, I am utilizing Reactive Form as shown below.

  public buildForm(): FormGroup {
    return this.form = this.fb.group({
        /* movie */
        'name': ['', [Validators.required, Validators.minLength(3)]],
        /* tickets*/
        'tickets': this.fb.array([this.buildTicketForm()])
    })
  }

  public buildTicketForm(): FormGroup {
    return this.fb.group({
        'name': ['',[Validators.required, Validators.minLength(3)]],
        'price': [0.00,[Validators.required, Validators.min(0.00)]],
    })
}

Now, my specific requirement is to have ticket validations triggered conditionally.

The ticket validations should apply only if there is a ticket name; otherwise, no need to validate.

Thank you!

Answer №1

To add custom validation to your form, you have the option of either creating a custom validator or implementing a conditional method like the example below:

  private setCustomValidators(formKey: string) {
    if (this.form.get('name').value !== null) {
      return [
        Validators.required,
        formKey === 'name' ? Validators.minLength(3) : Validators.min(0.00)
      ];
    }

After defining the custom validators, you can apply them when building your form using the FormBuilder:

public buildTicketForm(): FormGroup {
  return this.fb.group({
      'name': ['', this.setCustomValidators('name')],
      'price': [0.00, this.setCustomValidators('price')],
  });
}

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

Performing Cypress testing involves comparing the token stored in the localStorage with the one saved in the clipboard

I am currently working on a button function that copies the token stored in localStorage to the clipboard. I am trying to write code that will compare the token in localStorage with the one in the clipboard in order to verify if the copy was successful. H ...

What steps can I take to enhance the quality of my PDF files? Currently, I am utilizing Jspdf in conjunction with html

My current challenge involves generating a PDF file from my application. Although I am able to create a PDF, the quality is not up to par. When I download the PDF, I notice some discrepancies in text quality. While it's not terrible, it's also n ...

Discovering the data types for node.js imports

When starting a node.js project with express, the code typically begins like this - import express = require('express') const app = express() If I want to pass the variable 'app' as a parameter in typescript, what would be the appropri ...

Achieving the functionality of making only one list item in the navbar bolded upon being clicked using React and Typescript logic

Currently, in my navigation bar, I am attempting to make only the active or clicked list item appear bold when clicked. At the moment, I can successfully achieve this effect; however, when I click on other list items, they also become bolded, while the ori ...

Passing data from the <ion-content> element to the <ion-footer> element within a single HTML file using Ionic 2

In my Ionic 2 html page, I have a setup where ion-slide elements are generated using *ngFor. I am seeking a way to transfer the data from ngFor to the footer section within the same page. <ion-content> <ion-slides> <ion-slide *n ...

Error encountered: 'applePaySession.completeMerchantValidation' is not a valid object reference when attempting to process a successful apple pay payment

So, I'm having an issue with the user's payment going through but encountering undefined value when checking compatibility. I've been trying to debug this problem in my code snippet below: setCanDisplayApplePay() { var client = n ...

Formatting DateTime in Angular from an API

After confirming that the back end Java Rest API is indeed sending the correct date time format: 2018-05-17 19:08:25.203 Upon arrival to my Angular service, the date format mysteriously transforms into a large number: 1526555305203 The code snippet bel ...

What is the process for developing a personalized set of tslint rules?

I am looking to create a comprehensive TypeScript coding guideline that can be easily shared across various projects. Instead of repeatedly copying and pasting a tslint.json file, I aim to have a unified version to avoid any divergence issues. My guidelin ...

The proper order for logging in is to first validate the login credentials before attempting

I created a custom validation class to verify if a user is logged in before allowing them access to a specific page. However, after implementing this validation, my program no longer routes me to the intended component. Validation.ts export class UserVal ...

The 'IDatabaseDriver<Connection>' type does not meet the requirements of the 'AbstractSqlDriver<AbstractSqlConnection>' constraint

When attempting to define the type for the entity manager 'em' using a context, an error is encountered with the em type. The error states: Type 'IDatabaseDriver' does not satisfy the constraint 'AbstractSqlDriver'. The IDatab ...

Utilize toggle functionality for page rotation with rxjs in Angular framework

Managing a project that involves a container holding multiple cards across different pages can be overwhelming. To address this, the screen automatically rotates to the next page after a set time interval or when the user presses the space bar. To enhance ...

The "void" type cannot be assigned to the "ValidationErrors" type

export class MustMatchDirective implements Validator { @Input('mustMatch') mustMatch: string[] = []; validate(formGroup: FormGroup): ValidationErrors { return ValidateMatching(this.mustMatch[0], this.mustMatch[1])(formGroup); < ...

Is the @Output decorator with EventEmitter functioning properly for sibling components inside <router-outlet>?

Code Snippet from app.component.html <router-outlet> <app-header (cartRefresh)="updateCart(user_id)"></app-header> <app-breadcrumb></app-breadcrumb> </router-outlet> <app-footer></app-footer> Pull Cart Func ...

Obtain the Angular 2 Form object within a TypeScript class file for manual configuration of form properties

I have a form inside a PrimeNG dialog control. I need to handle two different submit methods based on certain conditions for this form, so I don't want to use the ngSubmit method in the form tag. Instead, I want to manually access the form object in m ...

Can you explain the significance of <this> within TypeScript generics?

Our application employs express along with TypeScript. While exploring their type definitions, I stumbled upon the following snippet and I'm curious about its meaning: export interface IRouter extends RequestHandler { all: IRouterMatcher<this& ...

Youngster listens for guardian's occurrence in Angular 2

While the Angular documentation covers how to listen for child events from parents, my situation is actually the opposite. In my application, I have an 'admin.component' that serves as the layout view for the admin page, including elements such a ...

Ways to resolve the issue of missing data display in Angular when working with the nz-table

Below is the code snippet: <nz-table #listTable nzSize="middle" [nzData]="data"> <thead> <tr> <th nzShowExpand></th> <th>Location</th> <th>Device</th> ...

Establishing a custom variable within a recurring component in a form for the purpose of validation

For my booking form process, I have different sections for adults, pensioners, children, and infants. While they all share the same four inputs, each section also has some unique input fields based on the type of customer. To streamline the duplicate secti ...

Why does TypeScript not recognize deconstructed arrays as potentially undefined variables?

When looking at the code snippet below, I was under the impression that the destructured array variables, firstName and lastName, would be classified as string | undefined. This is because the array being destructured could have fewer variables compared ...

Angular5: The property 'showNavigationArrows' cannot be bound to 'ngb-carousel' because it is not recognized as a valid property

Currently, I am utilizing ng-bootstrap 1.x.x alongside Angular5 and bootstrap4. My goal is to customize the NavigationArrows based on dynamic data, however, I am encountering an issue while trying to access it from HTML. Here is a snippet of my code: imp ...