How can an additional value be sent to the form validation method?

I have created a form group like this:

import { checkPasswordStrength } from './validators';

@Component({
....
export class PasswordComponent {
     ...

     this.userFormPassword = this.fb.group({
       'password': ['', [checkPasswordStrength]]
     });

In another TypeScript file, I have the checkPasswordStrength method

export function checkPasswordStrength(c: FormControl) {
  const SPECIAL_CHARACTERS_REGEX = /^\=\?$/;
  return SPECIAL_CHARACTERS_REGEX.test(c.value) ? null : {
    pwd: {
      valid: false
    }
  };
}

The above code is functioning properly. However, I now need to pass a pattern attribute to the setPwd method. So I attempted this:

this.userFormPassword = this.fb.group({
    'password': ['', [checkPasswordStrength('**')]]
});

and the updated checkPasswordStrength method is

export function checkPasswordStrength(c: FormControl, newPattern) {

But an error is being thrown. How can I successfully pass additional values to an external function?

Answer №1

It is recommended to adjust your function as follows:

export function setPasswordValidator(pattern: RegExp): ValidatorFn {
  return (control: AbstractControl): {[key: string]: any} | null => {
    const invalid = pattern.test(control.value);
    return invalid ? {'password': {value: control.value}} : null;
  };
}

this.formPassword = this.fb.group({
    'password': ['', setPasswordValidator('**') ]
});

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

Should you make multiple API calls or just one?

Currently in the process of developing an application that combines NodeJS and VueJs. I have created an API endpoint that provides all the necessary data. For instance, it may include The top Football Team The bottom Football Team The team with the most ...

JavaScript - turn off online connectivity

Is there a way to test my website for offline use by disabling connectivity on the bootstrap before anything loads, so that all data will be loaded from cache? I have tried various offline libraries such as this one, but I haven't found a way to prog ...

What is the proper method for activating the lights in a traffic light sequence?

I've been working on creating a traffic light sequence where each time the "change lights" button is pressed, the light is supposed to change. However, I'm facing an issue where the code only displays the red light and doesn't switch to ambe ...

Is there a way to prevent users from copying data or switching tasks when using my program or website?

Is it feasible to develop a website or application for Windows desktop machines that can remain focused until the user completes a specific task? For instance, if my YYY app/website is open and I require the user to input some text, I want to restrict the ...

Steps for refreshing a JavaScript function responsible for generating a table

Within the code snippet provided, there is a click event attached to a table row. Upon clicking a row, the script extracts the id value from the first column and triggers a REST call. Subsequently, a new table is constructed using a third-party function ca ...

Listen for the 'open' event on a node HTTP server

This question pertains to a previous inquiry I had about node httpServer encountering the EADDRINUSE error and moving to the next available port. Currently, my code looks like this: var port = 8000; HTTPserver .listen(port, function() { console.lo ...

The combination of TypeScript 2.6 and material-ui 1.0.0-beta.24's withStyles with react-router withRouter is resulting in the error message: "Property 'classes' is missing in type."

Using the high order components withStyles and withRouter together has been a smooth process so far. However, after upgrading to the latest versions of these components, an error occurred. Learn more about higher-order components List of packages used: ...

Unable to activate button click event using jQuery

I am using dot.js to enhance a specific webpage by adding a button that, when clicked, should insert text into a text field and then trigger another button to be clicked as well. To achieve this functionality, I have implemented a click handler for my butt ...

Creating circular artwork with PixiJS: A step-by-step guide

I am trying to create a circular image with specific height and width dimensions, but have not found a satisfactory solution. Currently, I can achieve this using a texture, however it is drawn multiple times in the same position. const test = new Graphic ...

What is the most effective way to send an email in PHP with a table format

<?php $result = mysqli_query($con, "SELECT * FROM cse"); $mail_data = ""; while ($row = mysqli_fetch_array($result)) { $Hallticket_No = $row['Hallticket No']; $Name = $row['Name']; $Email_ID = $row[&apos ...

Improving the method to change a string into a string literal in TypeScript

Utilizing a third-party tool that has specified editorStylingMode?: 'outlined' | 'underlined' | 'filled'; I have set the value in my environment.ts file (in Angular) as shown below export const environment = { productio ...

Ways to display notifications when the user is not actively browsing the website?

How can websites display notifications even when the user is not actively on the site? Take Facebook messenger, for instance. Even with the page closed, notifications still pop up. The same goes for Twitter, which also sends push notifications. I ...

Using Jquery and Ajax to pass an extra PHP variable to a server-side script

I am working with a dropdown select box where the selected option is sent to a server-side script using Ajax. <select id="main_select"> <option selected="selected" value="50">50</option> <option ...

Deciphering click event parameters in an AngularJS application

Currently, I am in the process of improving a feature in an existing application that has already been deployed. Unfortunately, all the JavaScript code is minified, and I only have access to the HTML files. I need to implement a function that triggers when ...

When set to synchronize:true in Typeorm, any changes to an entity will result in the many-to

As a newcomer to typeorm, I've encountered a peculiar issue with the synchronize: true setting in my ormconfig.js. Whenever I make changes to an entity with a Many-to-Many relationship, any data present in the join table prior to the entity modificati ...

Is it possible to configure Angular 6 without relying on node.js/npm?

Is there a way to set up and run an Angular application without relying on the Angular CLI or needing Node.js and npm commands in the terminal? I would greatly appreciate any suggestions regarding this matter. ...

What is the method for converting a JSON file into an array list?

I am looking to convert my JSON file into an arraylist that can be utilized to showcase the information on a webpage. Here is my HTML file snippet: var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if(this.readyState == 4 &a ...

Performance issues may arise in React styled-components when the state changes frequently during mousemove events

My current challenge involves implementing a parallax animation using react hooks and styled-components, but I am facing performance issues. The constant rerenders of components seem to be causing janky animations rather than smooth ones. Here are the sty ...

Sliding out list elements with jQuery ladder effect

I'm stuck on a seemingly simple task and need some guidance. facepalm. Currently, my site at this link has a menu list item issue where they all come out from the left side after the picture loads. I want them to slide out one by one, starting from t ...

utilization of dynamic templates within directives in the AngularJS framework

When it comes to deciding on a template based on the date, I came across an interesting example. However, in that specific example, the templates were so simple that strings could have been used. In my case, I prefer using PHP to generate the templates, so ...