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

Named functions in Typescript within functional components are the best practice for improving

How can I implement handleFoo using MyType['foo']? type MyType { foo: () => void } const Comp: React.FunctionComponent<{}> = () => { function handleFoo() {} return ... } I'm looking for a solution that doesn't inv ...

Customizing the appearance of antd Button using emotion and typescript

I've been attempting to customize an antd Button component using emotion in TypeScript, but I encountered an error when trying to implement the styled Button. The error message I received was: Type '{ children: never[]; }' is not assignab ...

Making a HTTP Get request for a single item in Ionic 2

I have successfully implemented an API to retrieve data and display it on the page. It works perfectly for a json response containing more than one object, as it follows a "matches" hierarchy. However, I am facing an issue when trying to print out data for ...

How to handle a Node.js promise that times out if execution is not finished within a specified timeframe

return await new Promise(function (resolve, reject) { //some work goes here resolve(true) }); Using Delayed Timeout return await new Promise(function (resolve, reject) { //some work goes here setTimeout(function() { resolve(true); }, 5000); } ...

Embrace the power of Angular2: Storing table information into

Custom table design Implement a TypeScript function to extract data from an array and populate it into a stylish table. ...

Using both Angular material design and Bootstrap together can provide a seamless

Is it feasible to integrate material design into an Angular app alongside bootstrap without any complications? I am aiming to leverage the grid system of twitter-bootstrap and incorporate the dialogues from material design... ...

Error: Unable to locate sportsRecord due to missing function

updated answer1: Greetings, I have updated the question with some detailed records and console logs for better understanding. sportsRecord = { playerTigers:[ {TigerNo: 237, TigerName: "Bird Bay Area", TigerkGroupNo: 1, isDefault: true ...

Angular outputting a basic static value

After searching extensively for a solution to my issue with Angular output, I have only come across ways to emit events. In my specific scenario, I have a parent component containing a router, and I need to dynamically change the title based on a value f ...

Unable to retrieve this information using $http callback

I am currently working with angular 1.5 and typescript, but I am facing an issue where I cannot access the 'this' property from the callback returned by the $http promise. Whenever I try to access a private method from the callback, 'this&a ...

Learn the method for triggering events with a strongly-typed payload in Vue 3 Composition API and TypeScript

I'm currently exploring Vue 3 Composition API along with TypeScript, particularly focusing on emitting events with a strictly typed payload. There's an example provided below, but I'm unsure if it's the most effective way to achieve t ...

Can you explain the significance of the "type" reserved word in TypeScript?

When attempting to construct an interface in TypeScript, I discovered that the word "type" is both a keyword and a reserved term. In Visual Studio 2013 with TypeScript 1.4, for instance, when defining the following interface: interface IExampleInterface { ...

What could be causing the TypeScript type error within this Effector effect subscriber?

Working on a front-end application utilizing React, Typescript, Effector, FetchAPI, and other technologies. Created an Effector effect to delete an item in the backend: export const deleteItemFX = createEffect({ handler: (id: string) => { return ...

Encountering errors in Angular when trying to access a property that is undefined using

One of the components I've created is being used in its parent component: <app-event-menu-nav [event]="event"></app-event-menu-nav> Below is the code for this component: import {Component, OnInit, ChangeDetectionStrategy, Input} ...

I am looking to personalize a Material UI button within a class component using TypeScript in Material UI v4. Can you provide guidance on how to achieve this customization?

const styling = { base: { background: 'linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)', border: 0, borderRadius: 3, boxShadow: '0 3px 5px 2px rgba(255, 105, 135, .3)', color: 'white', height: 48, ...

Whoops! Looks like there was a hiccup with the Vercel Deployment Edge Function, causing an

Every time I attempt to send a POST request to my Edge Function on Vercel Deployment, I encounter the following error message: [POST] /api/openai reason=EDGE_FUNCTION_INVOCATION_FAILED, status=500, user_error=true TypeError: Illegal invocation at app/api/ ...

Result of Mongodb aggregation operation

I've created a Property controller : //Retrieve Properties By Type const getPropertiesByType = async (req: Request, res: Response) => { const { cities, type } = req.query; const citiesArr = typeof cities === 'string' ? cities.spli ...

Simple method for adapting async/await function to function smoothly with observables

From my understanding, it's not recommended to use async/await methods in Angular. Therefore, I am exploring alternatives to achieve the desired functionality without using those methods. Currently, I am utilizing the canActivate function which call ...

Receiving an Error 404 "not found" when making a Node.js POST Request using an Angular application

I have been working on developing an API with Node.js that connects to an SQL Server database. While my GET requests are functioning properly, I am encountering errors with my POST request. To organize my node project, I have split it into two files - a ro ...

Revolutionize Your Web Development with ASP.NET Core and Angular 2 Integration using Webpack

I have started a new ASP.NET Core 1.0.1 project and I am working on integrating Angular 2 from scratch with Webpack Module Bundler. My goal is to use Hot Module Replacement (HMR) through ASP.NET Core SpaServices in order to avoid browser reloads, but I am ...

methods for sharing real-time data between parent and child components in Angular versions 2 and above

When working with Angular, we are familiar with parent to child communication using the @Input decorator. However, the challenge arises when we need to pass dynamic data from the parent to the child component. Imagine having a 'name' property def ...