A TypeScript function containing dual return statements

Consider the following code snippet:

export function forbiddenNameValidator(nameRe: RegExp): ValidatorFn {
  return (control: AbstractControl): { [key: string]: any } | null => {
    const forbidden = nameRe.test(control.value)
    return forbidden ? { forbiddenName: { value: control.value } } : null
  }
}

Source: https://angular.io/guide/form-validation#custom-validators

This function acts as a factory that accepts a regular expression to identify a specific prohibited name and generates a validator function.

The function returns a ValidatorFn, which in turn can return an error message or null.
So, what will actually be returned when using this function?

Answer №1

Consider using a reactive form as an example for adding validation. By including Validators.propertyname, you can specify the expected type of the second argument as either a ValidatorFn or ValidatorFn[] in formcontrol.

To implement custom validation in the first return, you need to include a ValidatorFn return value within the array.

The second return pertains to the logic executed when the validation process is triggered. This may involve running additional logic inside your ValidatorFn, such as a callback or promise.

new FormControl(this.hero.name, [
      Validators.required, --

      forbiddenNameValidator(/bob/i) // <-- Custom validator implementation.
    ]),

Include validation in the array -->   return (control: AbstractControl): {[key: string]: any} | null => {
                               const forbidden = nameRe.test(control.value);
Execute logic during validation -->   return forbidden ? {'forbiddenName': {value: control.value}} : null;
                             };

Think of built-in validations like Validators.required, which are included in the validation array and utilized when the form value changes. The logic written within this function is then executed, returning a value based on the specific use case or setting an error variable.

Answer №2

Here is a custom function that generates a ValidatorFn, which can either return an error message or null.
What do you think the final output will be?

You mentioned that forbiddenNameValidator produces a function that belongs to the ValidatorFn type.

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

Guide to encapsulating an asynchronous function in a promise

I am in need of wrapping an asynchronous function within a promise to ensure synchronous execution. The reason behind this is that I must obtain a result from the asynchronous function before proceeding with the program's execution. Below is the rele ...

Verify in Typescript if there is at least one value supplied

Looking for a solution: function takeOneOfOrThrow(firstOptionalVariable : string | undefined, secondOptionalVariable : string | undefined) { let result : string; if (!firstOptionalVariable && !secondOptionalVariable) { throw new E ...

Implement CSS to globally style material.angular's mat-card by customizing the background color

Looking for a way to globally change the background of mat-card on material.angular.io. I attempted adding the following code snippet to styles.css with no success. mat-card { background-color: purple; } ...

Best Practices for Utilizing NPM Modules with TypeScript

I am interested in developing an npm module using TypeScript. Can anyone suggest a best practice guide on how to start? Here are my questions: Node.js does not natively support TypeScript, so what is the recommended way to publish an npm module? Shoul ...

Distinguishing variations within subcategories that stem from a common origin

In my code example, I have two interfaces that both extend a common base interface. The "String" function takes an argument of type "StringAsset". My expectation was that if I were to call the "String" function and pass it a value of "NumberAsset", TypeScr ...

Angular component unable to access function within service

I'm a newcomer to Angular and I'm encountering an issue with my service. In my service, I have a function to post a survey and a component. The problem lies in my component not being able to see the service. Additionally, when using UserIdleModul ...

Typescript with Angular: Despite having 7 values in the map, Map.get is returning undefined

Why does Map.get always return undefined when using a number from a form element (extra1) in this code snippet? extraById = new Map<number,Extra>(); @Input() extra1: number = -1; formChanged(carConfigurationFormChanged : any) { const index ...

Updating the background color using typescript

Before transitioning to angular development, I had experience working with vanilla Javascript. I encountered a challenge when trying to modify the css properties of specific elements using Typescript. Unfortunately, the traditional approach used in Javascr ...

Issue with Angular Material date picker: Date Parsing UTC causing dates to display as one day earlier

After exploring numerous threads related to this issue and spending several days trying to find a solution, I may have stumbled upon a potential fix. However, the workaround feels too messy for my liking. Similar to other users, I am encountering an issue ...

Raycaster in Three.js fails to recognize clicks on objects

Having trouble detecting clicks on Three.js objects using a raycaster in Angular? Here's the code I'm working with: @Component({ selector: 'app-viewer-3d', templateUrl: './viewer3d.component.html', styleUrls: ['./vi ...

Passing a callback to a third-party library resulted in an unexpected error

My React+TypeScript code utilizes a component from a third-party library. <ThirdPartyComponent onSelect={(value: any) => {...}} /> The eslint-typescript tool is flagging this as an error: Unexpected any. Specify a different type. eslint(@type ...

Any URLs that are requested through HTTP on the server must be for absolute server rendering

I've encountered an error while working on Angular 4 CLI + Universal, and I need help resolving it. I recall that it should work with relative paths, but I'm unsure how to achieve this. ERROR Error: URLs requested via Http on the server must b ...

Utilize the fetch function within a React functional component

I have been experimenting with different methods to fetch data only once before rendering, but I am encountering some challenges: It is not possible to call dispatch in componentDidMount as there is a restriction that it can only be done in Functional c ...

Effective shop / multiple replicated element development

I currently have an Angular component known as "runner" which appears three times on the same screen. This component features two connected dropdown menus - one named "Models" and the other named "Definitions". Each model can have multiple definitions ass ...

Combining namespaces in Typescript declaration files

Currently, I am attempting to combine namespaces from d.ts files. For example, when I attempt to merge namespaces in a single file, everything works as expected. declare namespace tst { export interface info { info1: number; } var a: ...

Ways to enhance the Response in Opine (Deno framework)

Here is my question: Is there a way to extend the response in Opine (Deno framework) in order to create custom responses? For instance, I would like to have the ability to use: res.success(message) Instead of having to set HTTP codes manually each time ...

NodeJS on Cloudlinux requires that the node modules for applications be stored in a distinct folder (virtual environment) designated by a symbolic link known as "node_modules"

I recently encountered an issue while trying to deploy my Nodejs/TypeScript web application on my cpanel shared hosting. The error I received stated: * Cloudlinux NodeJS Selector requires the node modules for the application to be stored in a separate f ...

NG8001: The element 'app-servers' is unrecognized

Oh no! https://i.sstatic.net/fzYWO0w6.png Issue https://i.sstatic.net/xGunjgiI.png https://i.sstatic.net/26gzDLJM.png I've tried everything but can't seem to fix it I'm using the same selector but the problem persists It's supposed ...

Error TS2305: The module "@prisma/client" does not have an export named "User"

Setting up a Gitlab CI for my nestjs project using prisma has been my current challenge. I keep encountering this error when running the pipeline: see image here This is what my .gitlab-ci.yml looks like: image: node:latest stages: - build build: st ...

ESLint encountering a "Module path unresolved" issue in conjunction with SAM Serverless Monorepo

In the process of developing a basic Hello World function for AWS Lambda/APIGateway, I aim to integrate ESLint and Typescript features. Typically, when working with Typescript and ESlint, inclusion of the eslint-plugin-import package and specifying the ext ...