Angular 14 Custom Validator Assistance

I need help understanding how to incorporate a custom validator in my reactive form. I have 15 fields, and 3 of them are related to the custom validators "tcpPorts", "udpPorts", and "icmp" (a checkbox). The requirement is that at least one of these three fields must contain a value in order to submit the form. How can I create the appropriate validator for this scenario?

Here is an excerpt from my component.ts file where the form is defined:

 newFWXForm = this.fb.group(
{
  sspSelect: ["", Validators.required],
  requester: [this.loggedInUser],
  requesterContactInfo: [this.loggedInUserEmail],
  fwxDescription: ["", Validators.required],
  durationTypeSelect: ["Permanent", Validators.required],
  durationDate: [""],
  infraSelect: [""],
  sourceIPs: ["", Validators.required],
  DestAnyCheck: [false],
  SrcAnyCheck: [false],
  icmp: [false, atleastOneValidator()],
  destinationIPs: ["", Validators.required],
  tcpPorts: ["", atleastOneValidator()],
  udpPorts: ["", atleastOneValidator()],
  addDirectory: new FormControl(false),
},
{ Validators: [] }

In addition, I have started working on a custom Validator function but would appreciate any guidance or tips on improving it:

export function atleastOneValidator(): ValidatorFn {
return (control: AbstractControl): ValidationErrors | null => {};
}

Thank you for your assistance!

Answer №1

If you want to ensure that at least one of the child FormControls in a FormGroup has a value, you can create a custom Validator for it.

Here is an example implementation:

export function requireAtLeastOne(controls: string[]): ValidatorFn {
  return (group: AbstractControl): ValidationErrors | null => {
    // Implement your validation logic here, such as checking if at least one control has a truthy value
    const isValid = controls.some(
      (controlName) => group.get(controlName)?.value
    );
  
    return isValid ? null : { requireAtLeastOne: true };
  };
}

Then, you can apply this validator to the FormGroup by passing an array of control names to check.

myForm = this.fb.group(
  {
    // Define your form controls here
  },
  { 
    validators: [requireAtLeastOne(['control1', 'control2', 'control3'])]
  }
)

Cheers!

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

typescriptExtract generic type from TypedDocumentNode<MyType, unknown> using introspection

I am currently utilizing a library that allows me to retrieve the type from a returned variable within a function. const myVar = gql(somestring) // The library function is called gql type myVarType = typeof myVar // The resultant value of myVarType is Typ ...

Using custom elements in both React and Angular is not supported

After successfully creating a custom element in React using reactToWebComponent, I integrated it into a basic HTML file like this: <body> <custom-tag></custom-tag> <script src="http://localhost:3000/static/js/bundle.js&quo ...

"Observables in RxJs: Climbing the Stairs of

Previously, I utilized Promise with async/await syntax in my Typescript code like this: const fooData = await AsyncFooData(); const barData = await AsyncBarData(); ... perform actions using fooData and barData However, when using RxJs Observable<T> ...

A guide on converting JSON to TypeScript objects while including calculated properties

I have a standard JSON service that returns data in a specific format. An example of the returned body looks like this: [{ x: 3, y: 5 }] I am looking to convert this data into instances of a customized TypeScript class called CustomClass: export class ...

What is the importance of a subclass providing services to a superclass in Angular?

While exploring some Angular code today, I stumbled upon this interesting snippet: export class ContentFormComponent extends FormBase { ... constructor( private authService: AuthService, private apiService: ApiService, private segmentService: Segme ...

What is the method for obtaining the properties of a type as an array in Typescript?

In the given scenario: class Foo { constructor( private one: string, private two: string, private three: string) { } } Is there a way to create an array containing the type's properties? For example, I need to gene ...

Node.js does not allow the extension of the Promise object due to the absence of a base constructor with the required number of type

I'm trying to enhance the Promise object using this code snippet: class MyPromise extends Promise { constructor(executor) { super((resolve, reject) => { return executor(resolve, reject); }); } } But I keep encou ...

Set up SystemJS to properly load my Angular 2 component module

Recently, I made the switch from ng1 to ng2. I successfully imported Angular 2 and its modules into my project: <script src="/node_modules/systemjs/dist/system.src.js"></script> <script src="/node_modules/rxjs/bundles/Rx.js"></script& ...

Experiencing the 'invalid_form_data' error while attempting to upload a file to the Slack API via the files.upload method in Angular 8

I am currently working on a project that involves collecting form data, including a file upload. I am trying to implement a feature where the uploaded file is automatically sent to a Slack channel upon submission of the form. Despite following the guidance ...

What is the best way to filter an array of objects and store the results in a new variable list using typescript?

On the lookout for male objects in this list. list=[ { id: 1, name: "Sam", sex: "M"}, { id: 2, name: "Jane", sex: "F"}, { id: 3, name: "Mark", sex: "M"}, { id: 4, name: "Mary, sex: "F& ...

Does Nativescript successfully utilize AOT Compilation even with the `Compiler` package still included?

I'm running this command: npm run ns-bundle --android --build-app --uglify The command is successful (you can find the complete log here). After navigating to the report folder (generated by webpack-bundle-size-analyzer), I found these two files: ...

Angular - Turn off date selection in datepicker when toggle switch is activated

I am currently utilizing angular material and I need to figure out how to deactivate the datepicker after toggling a slide. Below is my upload form equipped with a datepicker: <form #uploadForm="ngForm" (keydown.enter)="$event.preventDefault()" (ngSub ...

Angular 11 now includes the ability to implement lazy loading for modules

Here is the configuration of my app-routing.module.ts: const routes: Routes = [ { path: 'login', component: LoginComponent }, { path: '', canActivate: [AuthGuard], component: HomeComponent, children ...

How can I utilize a variable to define the key for the template HTML property in Angular 7?

Is there a method in Angular 7+ that allows me to incorporate a variable as the template html property key? I am trying to achieve something like the following: <path [attr.data-**<use-variable-here>**]="edge.id"></path> ...

Replace interface with a string

Is it possible to override an interface with a string in TypeScript? Consider this example: type RankList = "Manager" | "Staff" interface EmployeeList { id: string, name: string, department: string, rank: "Staff&q ...

Enhance the variety of types for an external module in TypeScript

I am in the process of migrating an existing codebase from a JavaScript/React/JSX setup to TypeScript. My plan is to tackle this task file by file, but I have a question regarding the best approach to make the TypeScript compiler work seamlessly with the e ...

The Angular project seems to be experiencing technical difficulties following a recent update and is

Recently, I made the transition from Angular 6 to 8 and encountered two warnings during the project build process that I can't seem to resolve. Despite searching online for solutions, nothing has worked so far. Any help would be greatly appreciated. ...

The cursor in the Monaco editor from @monaco-editor/react is not aligning with the correct position

One issue I am facing with my Monaco editor is that the cursor is always placed before the current character rather than after it. For example, when typing a word like "policy", the cursor should be placed after the last character "y" but instead, it&apos ...

What is the meaning of '=>' in typescript/javascript?

I keep coming across lots of '=>' in the code I found on the internet. Could someone please explain it to me as if I were 5 years old? (I'm searching for the specific code, and I'll share it here once I locate it).. Found it: ...

Tips for constructing node.js projects using local versions of the dependencies?

Recently, I've been tackling a rather intricate node.js project (find it at https://github.com/edrlab/thorium-reader/) while trying to incorporate local versions of certain dependencies. Surprisingly, I can successfully build and execute the project ...