You cannot assign multiple properties with the same name to an object literal

I am facing an issue with two validator functions in my TypeScript file. The first validator checks if a user enters a new password same as the old one, displaying an error if so. The second validator ensures that "new password" and "confirm password" must match. The problem arises when I include both functions in my ts file, resulting in the following error message:
An object literal cannot have multiple properties with the same name.

The error specifically points to the "validators:" part of "validators: matchValidator('newPassword', 'confirmPassword'),"


What could be causing this error?

Below is the code snippet:

.ts file:

import {
  AbstractControl,
  AbstractControlOptions,
  FormBuilder,
  FormControl,
  FormGroup,
  Validators,
} from '@angular/forms';
import { AppConfig } from 'src/app/_common/configs/app.config';
import { Component } from '@angular/core';
import { PasswordRegex } from 'src/app/_common/constants';
import { matchValidator } from 'src/app/_common/validators/match.validator';
import { notEqualValidator } from 'src/app/_common/validators/match.validator';

@Component({
  selector: 'app-change-password',
  templateUrl: './change-password.component.html',
  styleUrls: ['./change-password.component.scss'],
})
export class ChangePasswordComponent {
  appConfig = AppConfig;
  oldPassword = new FormControl(null, [
    (c: AbstractControl) => Validators.required(c),
    Validators.pattern(PasswordRegex),
  ]);

  newPassword = new FormControl(null, [
    (c: AbstractControl) => Validators.required(c),
    Validators.pattern(PasswordRegex),
  ]);

  confirmPassword = new FormControl(null, [
    (c: AbstractControl) => Validators.required(c),
    Validators.pattern(PasswordRegex),
  ]);

  changePasswordForm = this.formBuilder.group(
    {
      oldPassword: this.oldPassword,
      newPassword: this.newPassword,
      confirmPassword: this.confirmPassword,
    },
    <AbstractControlOptions>{
      validators: notEqualValidator('oldPassword', 'newPassword'),
      validators: matchValidator('newPassword', 'confirmPassword'),
    }
  );

  constructor(private formBuilder: FormBuilder) {}

  onSubmit(): void {
    if (!this.changePasswordForm?.valid) {
      return;
    }
  }
}

match.validator.ts file:

import { FormGroup } from '@angular/forms';

export function matchValidator(controlName: string, matchingControlName: string) {
  return (formGroup: FormGroup) => {
    const control = formGroup.controls[controlName];
    const matchingControl = formGroup.controls[matchingControlName];

    if (matchingControl.errors && !matchingControl.errors['matchValidator']) {
      return;
    }

    if (control.value !== matchingControl.value) {
      matchingControl.setErrors({ matchValidator: true });
    } else {
      matchingControl.setErrors(null);
    }
  };
}
export function notEqualValidator(controlName: string, matchingControlName: string) {
  return (formGroup: FormGroup) => {
    const control = formGroup.controls[controlName];
    const matchingControl = formGroup.controls[matchingControlName];

    if (matchingControl.errors && !matchingControl.errors['notEqualValidator']) {
      return;
    }

    if (control.value == matchingControl.value) {
      matchingControl.setErrors({ notEqualValidator: true });
    } else {
      matchingControl.setErrors(null);
    }
  };
}

Answer №1

To enhance security, consider using an array for the validators property:

passwordForm = this.formBuilder.group(
  {
    currentPassword: this.currentPassword,
    newPassword: this.newPassword,
    confirmPassword: this.confirmPassword,
  },
  <FormControlOptions>{
    validators: [
      customValidator('currentPassword', 'newPassword'),
      passwordMatchValidator('newPassword', 'confirmPassword')
    ]
  }
);

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

The validation of radio input signals results in an error being returned

For a while now, I've been trying to solve the issue with radio button validation in my current project. Surprisingly, it works fine when there are no other functions in the form besides the radio buttons themselves. I suspect that the problem lies wi ...

Error Alert: Accessing the 'email' property on the 'UserCredential' type in Angular and Firebase is not allowed

import { Injectable } from '@angular/core'; import { Router } from '@angular/router'; import { User } from './../classes/user'; import { AlertService } from './alert.service'; import { Alert } from './../classes ...

Testing units in Angular using different sets of test data

When it comes to unit testing a C# method with different sets of data, the Theory and InlineData attributes can be used to pass multiple inputs for testing purposes. [Theory] [InlineData("88X", "1234", "1234", "1234")] [InlineData("888", "123X", "1234", " ...

Troubleshooting auxiliary routes in Angular: why won't they work

I am facing an issue where I am trying to load components into a router outlet nested within another component. Within my ProgramComponent (with the selector app-program), I have defined a router outlet. <a routerLink="admin1">One</a> <a ro ...

What is the best method for compressing and decompressing JSON data using PHP?

Just to clarify, I am not attempting to compress in PHP but rather on the client side, and then decompress in PHP. My goal is to compress a JSON array that includes 5 base64 images and some text before sending it to my PHP API. I have experimented with l ...

Questioning the syntax of a TypeScript feature as outlined in the documentation

I have been studying the Typescript advanced types documentation, available at this link. Within the documentation, there is an example provided: interface Map<T> { [key: string]: T; } I grasp the concept of the type variable T in Map. However ...

Subscribe to the service in Angular and make repeated calls within the subscription

What is the most effective way to chain subscriptions in order to wait for a result before starting another one? I am looking for something similar to async/await in Javascript, where I need the result of the first call to trigger the next one. Currently, ...

What are the steps to resolving an issue in a Jest unit test?

In my ReactJs/Typescript project, I encountered an issue while running a unit test that involves a reference to a module called nock.js and using jest. Initially, the import statement was causing an error in the .cleanAll statement: import nock from &apos ...

Ways to resolve the Ionic v1 deprecation error problem

I am facing a problem with an Ionic v1 deprecation error, causing it to not work properly. ionic build ios ionic emulate android The basic commands are failing to produce the desired outcome. Is there a way to resolve this issue? Note: My application is ...

The module '@angular/core' is not found in the Visual Studio Code IDE

It seems like a straightforward code. However, I am encountering the error cannot find module '@angular/core'. course.component.ts import {Component} from '@angular/core' @Component({ selector: 'courses' }) export clas ...

Enhance your Next.js routing by appending to a slug/url using the <Link> component

In my Next.js project, I have organized my files in a folder-based structure like this: /dashboard/[appid]/users/[userid]/user_info.tsx When using href={"user_info"} with the built-in Next.js component on a user page, I expect the URL to dynamic ...

What is the simplest way to incorporate Vue with Typescript, without the need for a complex build setup?

I've been spending the last couple of days experimenting with my basic ASP.NET Core website set up for Typescript 2.9, but unfortunately, I haven't made much progress. My main goal is to keep the front-end simple, with just single Vue apps on eac ...

Mastering the art of Promises and handling errors

I've been tasked with developing a WebApp using Angular, but I'm facing a challenge as the project involves Typescript and asynchronous programming, which are new to me. The prototype already exists, and it includes a handshake process that consi ...

The requested module cannot be located, were you referring to "js" instead?

I am currently developing a React application using webpack and typescript. I have integrated the dependency react-financial-charts into my project, and it is properly specified in the package.json. Inside the node_modules directory, there are two folders ...

I am unable to enter any text in an angular modal

Currently, I am facing an issue where I am unable to click on the search input field within a modal. The goal is to implement a search functionality in a table displayed inside a modal window. The idea is to have a list of hospitals where users can view d ...

The toISOString() method is deducting a day from the specified value

One date format in question is as follows: Tue Oct 20 2020 00:00:00 GMT+0100 (Central European Standard Time) After using the method myValue.toISOString();, the resulting date is: 2020-10-19T23:00:00.000Z This output shows a subtraction of one day from ...

What's the best way to replicate a specific effect across multiple fields using just a single eye button?

Hey everyone, I've been experimenting with creating an eye button effect. I was able to implement one with the following code: const [password, setPassword] = useState('') const [show, setShow] = useState(false) <RecoveryGroup> ...

Loop through a collection of elements of a certain kind and selectively transfer only certain items to a different collection of a different kind

When working with typescript, I am faced with the challenge of dealing with two arrays: interface IFirst{ name: string; age: number } interface ISecond { nickName: string; lastName: string; } myFirstArray: IFirst[]; mySecondArray: ISe ...

Are there any methods to utilize Zod for validating that a number contains a maximum of two decimal places?

How can I ensure that a numeric property in my object has only up to 2 decimal digits? For example: 1 // acceptable 1.1 // acceptable 1.11 // acceptable 1.111 // not acceptable Is there a method to achieve this? I checked Zod's documentation and sea ...

Validation Form Controls

Here is a piece of code that works for me: this.BridgeForm = this.formBuilder.group({ gateway: ["", [Validators.required, Validators.pattern(this.ipRegex)]], }); However, I would like to provide more detail about the properties: this.BridgeF ...