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

Unable to establish a connection with the TCP server on CloudFoundry, although the localhost node.js is functioning properly

I am experiencing difficulty connecting to my TCP server example that is running on CloudFoundry. Interestingly, when I run my app.js file on a local node.js installation, everything works perfectly. Upon using vmc push to deploy on CloudFoundry, the servi ...

Discovering the correct element and typing for an HTML attribute through JavaScript

We are currently working on test automation and I am looking for a way to identify the Element and Type associated with it within an html (Data-qa) attribute. For example, when looping through, the Element is identified as input and the type is radio. < ...

Include a header in the API HTTP call for Angular 2 and Ionic 2

Working on my Ionic 2 app, I am using Angular 2 Http to retrieve JSON from an API. However, I am struggling to send the app-id, app-key, and Accept as headers in the main code snippet below: import {Component} from '@angular/core'; import {NavC ...

Having difficulties with JavaScript's if statements

I'm facing an issue with my JavaScript code that is meant to modify the value of a price variable and then display the updated price. The problem arises when I have multiple select options, as the price only reflects the ID of the last statement. Here ...

Angular appears to be having trouble with localStorage functionality

Having an issue with my service that interacts with a local NOTES object array using localStorage. Whenever the page refreshes, the previously entered data is lost and only the initial data in the const NOTES array remains. Can't seem to figure out wh ...

What is the best approach to send data to the parent when closing $mdDialog?

When I open a Dialog Window, it has its own controller. Is there a way for me to modify data in the differentController that belongs to the Dialog Window and then send the modified data back to the parent controller when the dialog is being removed? fun ...

"Enhance User Experience with jQuery Autocomplete using String Arrays

Within my web form model (AdtFormModel), there is a variable: public List<String> TemoinsVille { get; set; } I opted for a list structure as I intend to allow users to dynamically add more 'TemoinsVille' inputs in the form. Currently, ...

What is the process for sending a parameter in getStaticProps within Next.js

Is there a way in NextJS to call an API when a user clicks the search button and display the relevant result? Thanks for your input! The API I'm currently utilizing is , with "Steak" referring to the specific food item of interest. In my development ...

Constructing Browserify with dependencies containing require statements within a try-catch block

When attempting to integrate timbre.js (npm version) with Browserify, I encountered an issue where require statements for optional dependencies were enclosed in a try statement (check the source here). This resulted in a browserify build error displaying: ...

I. Discovering the Step-by-Step Guide on Retrieving User Information from Facebook Upon Generating App

I have set up a Facebook login for user registration on my website. However, I am only able to retrieve the profile name and user ID from Facebook. How can I access the email and other user information? Here is the data I am currently receiving from Faceb ...

Navigate to the login page in Angular 2

Initially, the template login (login.component) needs to be called first. Once the login is complete, then app.component will be loaded. Is it possible to achieve this? And if so, how can I do it? Edited Question: I am already using CanActivate. Apologi ...

Having trouble executing a method from a template in Angular 5?

Angular has a useful capability that almost every developer has utilized at some point: calling methods from templates. I've personally been using this feature for months without any issues. However, recently I encountered a problem. I have a menu co ...

Type with self-reference in index

Looking to create an interface with a mix of known and unknown members that should all have the same type. Here's what I have in mind: interface Foo { name?: string; [others: string]: Foo; } This setup would allow me to create something like ...

Selecting from a variety of options presented as an array of objects

I am currently working on a component that allows users to select roles: https://i.stack.imgur.com/bnb9Y.png export const MultipleSelectChip = ({ options, label, error, onRolesUpdate, }: Props) => { const theme = useTheme(); const [selected ...

html inserting line break using label

I am attempting to dynamically set text to a label using jQuery. However, I am having trouble getting the <br> or \n to create new lines. Instead, all the text displays on the same line and wraps around. If you want to see my code in action, ch ...

The event listener for the custom cursor in Nuxt.js is failing to work properly when the route

I am currently in the process of constructing a new website for our studio, but am encountering difficulties with getting the custom cursor to function correctly. I implemented a custom cursor using gsap, and it worked perfectly; however, once I navigate t ...

Creating and accessing files within the `dist` folder in Angular 5: A comprehensive guide

After deploying my Angular 5 app to Cloud Foundry, a file named app-number-version is automatically generated in the dist folder with just the version number (e.g., "1.0.0"). My goal is to show this version number in the navigation bar of our app's H ...

Troubleshooting: Issues with accessing object properties in a function in AngularJS

In my controller, I have a function that checks the day and changes the isOpen property of an object based on the time. The object is retrieved using the code snippet below: $http.get('js/data.json').success(function(data) { $scope.locations = ...

Trouble embedding iframes in local files?

I have recently created a file which includes the following code: <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8> <style> iframe { height: 500px; width: 600px; } ...

Restrictions on file sizes when using multer for file uploads

I am currently working on a file uploader that needs to support various file types, such as images and videos. My goal is to apply different maximum file sizes for images (10MB) and videos (100MB) using a single instance of Multer, a middleware designed fo ...