What steps should I take to troubleshoot a 'TypeError: Cannot read property 'value' of null' issue in Angular 12?

I encountered an issue in my Angular 12 project while trying to implement a service called customValidation. The purpose of this service is to validate password patterns and ensure that the password and confirm password fields match before submitting the form. However, every time I run the project, I receive an error message stating "TypeError: Cannot read property 'value' of null" from the browser console. This error seems to be pointing to the matchPassword function within the customValidation service. Can anyone help me figure out what I missed?

Below is my customValidation.service.ts code:

export class CustomvalidationService {
  constructor() {}

  patternValidator(): ValidatorFn {
    return (control: AbstractControl): { [key: string]: any } => {
      if (!control.value) {
        return null!;
      }
      const regex = new RegExp('^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9]).{8,}$');
      const valid = regex.test(control.value);
      return valid ? null! : { invalidPassword: true };
    };
  }

  matchPassword(c: AbstractControl): { [key: string]: any } {
    let passwordControl = c.get(['password']);
    let confirmPasswordControl = c.get(['cPassword']);

    if (passwordControl!.value !== confirmPasswordControl!.value) {
      return { passwordMismatch: true };
    } else {
    return { passwordMismatch: false };
  }
 }
}

Here is my registration.component.ts file:

export class userRegisterComponent implements OnInit {
  aino: number = new Date().getFullYear();

  registerForm!: FormGroup;
  submitted = false;

  fname = new FormControl('', [Validators.required]);
  email = new FormControl('', [Validators.required, Validators.email]);
  password = new FormControl('', Validators.compose([Validators.required, this.customvalidator.patternValidator]));
  cPassword = new FormControl('', Validators.compose([Validators.required, this.customvalidator.matchPassword]));
  uPass = new FormControl('', [Validators.required]);


  constructor(
    public authService: AuthService,
    private customvalidator: CustomvalidationService
  ) {}

  ngOnInit(): void {
    this.registerForm = new FormGroup({});
  }

  // function to submit the registration form

  onRegister() {
    this.submitted = true;
    if (this.registerForm.valid) {
      alert(
        'Form submitted successfully! \n Check the values in the browser console'
      );
      this.authService.SignUp('email.value', 'password.value');
      console.table(this.registerForm.value);
    } else {
      alert('Please fill all fields. Thank you!');
    }
  }
}

Answer №1

Your password declaration for passwordControl in the service contains a misspelling.

let passwordControl = c.get(['passowrd']);

The correct version should be:

let passwordControl = c.get(['password']);

Answer №2

It is recommended that the Validator function should now return a function, instead of an Object like { passwordMismatch: true }

To update your matchPassword function, consider modifying it to something similar to the following:

 matchPassword(...) {
    return (group: AbstractControl): ValidationErrors | null => {...};
 }

In a related scenario, here is an example of a password matching validator:

import { AbstractControl, ValidationErrors } from '@angular/forms';

// custom validator to check that two fields match
export function MustMatch(controlName: string, matchingControlName: string) {
  return (group: AbstractControl): ValidationErrors | null => {
    const control = group.get(controlName);
    const matchingControl = group.get(matchingControlName);

    return control.value === matchingControl.value ? null : { notSame: true };
  };
}

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

How can I retrieve the express Application within a REST API?

After reviewing Massive's documentation and learning that saving the connection object to Express's application settings can help reduce database connection execution time, I encountered a problem. How can one access the Express app variable when ...

The variable 'xxx' is not defined in this context

I am attempting to incorporate a dark theme into ngx-charts, and I'm relatively new to using less. Here is the code snippet: My IDE is showing an error message "Cannot find variable 'color-bg-darker'" which leads to compilation failure. Err ...

The tsconfig within the module directory fails to supersede the extended tsconfig properties present in the parent directory

Within the directory store/aisle/fruits, there is a tsconfig.json file: { "compileOnSave": true, "compilerOptions": { . . "target": "es6", "noEmitOnError" : true, "noEmitHelpers ...

Lazy loading child routes in Angular 4 encounters issues when the child routes share the same path

I have developed an application that features a contact list with the capability to select and view detailed information about a single contact. The contact detail page includes tabs for sub-information such as profile, touch points, and contact info. Belo ...

Karma Jasmin is puzzled as to why her tests are failing intermittently, despite the absence of any actual test cases

In this snippet, you will find my oninit method which I am instructed not to modify. ngOnInit(): void { this.setCustomizedValues(); this.sub = PubSub.subscribe('highlightEntity', (subId, entityIdentifier: string) => { ...

Unidentified Angular NgRX action

After building my Angular application using NgRX, I integrated actions, reducers, services, and effects. However, when trying to access the action in the component code, I encountered the following error: Error: Property 'GetEmployees' does no ...

Customizing event typings for OpenTok in Typescript

Currently, I am working on integrating chat functionality using the 'signal' events with the OpenTok API. Here is my event listener that successfully receives the signal: // Listen for signal CHAT_MESSAGE sess.on('signal:CHAT_MESSAGE', ...

Is there a way to navigate directly to the code in a TypeScript type definitions index.d.ts file within Visual Studio Code?

When I command-click on the express() function, it takes me to its definition: const app = express(); In vscode, it leads me to this line in an index.d.ts file: declare function e(): core.Express; However, when I try to jump to the definition of e(), i ...

Implementing custom error handling in GraphQL using TypeORM and Apollo

Hey there, I'm currently working on implementing a custom error handling feature in my application. An example scenario is when a user tries to create an account with an email that already exists: { "errors": [ { "message": "The email exi ...

Steps for transforming a complex nested object into an observable and extracting specific values

First of all, I'm wondering if this is the recommended approach in Angular. Can I achieve this?: I have a JSON object with multiple levels of children and I need to console.log specific subsubsubsubchildren. Here is the code I tried: const observable1 ...

Ensuring ng-multiselect-dropdown validation in Angular 5

I have implemented a multi-select dropdown feature in my application by utilizing the npm package "ng-multiselect-dropdown". As I am working with a template-driven form, I am now looking to add validation for this multiselect functionality. For more infor ...

The listener for @ok is not being activated when using jest-test-utils with b-modal in vue-bootstrap

I have implemented the vue-bootstrap b-modal feature with the @ok="save" hook Here is a snippet of mycomponent.vue: <template> <div> <b-button @click="add">open modal</b-button> <b-modal static lazy id="modal-detail" ...

What is the best way to provide props to a Link Router component?

Hey there, I'm looking to pass props to another component using Link Router My approach involves using a Class Component constructor(props: IBanner) { super(props); this.state = { jobCategories: [], jobKeyword: "", ...

What is the correct version compatibility matrix for Expo, NPM, Node, React Native, and TypeScript?

Currently, I am in the process of setting up React Native with TypeScript. Here are the steps I followed: npx react-native init MyApp --template react-native-template-typescript I made sure to install TypeScript as well: npm install -g typescript ' ...

Is it possible that multiple identical queries are being executed in succession when adjusting the amount of data being displayed?

Why do multiple identical GET requests get executed when changing the data amount? [HPM] GET /api/users/get_all?search=&order=asc&pageSize=25&page=1 -> http://localhost:5000 GET /api/users/get_all?search=&order=asc&pageSize=2 ...

Plugin for inserting script tags using Gulp

Is there a plugin available that can automatically include <script> tags in HTML files? Currently, I am using tsify and browserify to compile my typescript files into a single JavaScript file. While this process works well, it can be inconvenient dur ...

Encountering an error due to an invalid type union when creating a new instance of a

My TypeScript code includes a Logger class that has an optional options parameter in its constructor. The options parameter includes a class generic C which represents custom levels. These custom levels are used within the class for methods like log(level: ...

The Material UI Grid is not compatible with the Chrome DevTools Device Toolbar and may not function properly

Using MUI v5 with React and Typescript has been an interesting experience for me. When I utilize the Grid system, I set options like xs sm md lg to define item width. Interestingly, setting just xs or sm works fine, but when I include md, other options su ...

Customize validation timing in Angular Reactive Forms

One common query about the conditional validator is understanding when exactly it gets triggered. Imagine a simple form with just two fields this.form = formBuilder.group({ emailRequired: [false], emailRecipients: [''] }); Now, let's s ...

In Angular ngrx, when using parameters 'action' and 'action', it is important to note that they are not compatible with each other. Additionally, it is crucial that the property 'payload' is not

I have recently started working with Angular and I am using ngrx to manage the state in my application. However, when I try to compile the code, I encounter an error that says 'Types of parameters 'action' and 'action' are incompat ...