0
votes

I am trying to create a ValidatorFn that will be used in several components which represent custom reactive form controls. My initial idea was to generate a TypeScript class, create a public static function (or several) there and then just use it like so: myFGroup.setValidators(ReactiveValidators.myValidator).

The problem is, although I imported this ReactiveValidators class in the app.module and added it to declarations: [], I still get the favorite error:

error TS2307: Cannot find module 'src/app/validators/reactive-validators'

Can someone tell me what I am doing wrong? Also, is this approach even a good one at all?

2
Did you add @Component inside your ReactiveValidators class ? Did you add ReactiveValidators in a module's declaration ? If so, remove it. It is not an Angular Component. - Random
No, I didn't add @Component. Thanks for pointing that out. But how can I export that ValidatorFn or the class that wraps it correctly? I'm not keen on pasting it in several files :) - dzenesiz
using myFGroup.setValidators(ReactiveValidators.myValidator) will work, where ReactiveValidators is in its own file anywhere in your app. - Random
That's what I thought - and did. I even generated a ReactiveValidators class using ng generate class, but I still get the error above. - dzenesiz
I figured it out while editing the answer... the correct import statement is import { maxInputLengthValidator } from '../../validators/reactive-validators'. Notice the relative path. And, for some reason, VS Code auto import uses absolute path, the one in the error message. I fixed the path, now it works. Thanks for the help! - dzenesiz

2 Answers

1
votes

A ValidatorFun is just a function, which is not required to be in any class. You can simply create a ts file with exported Validator functions.

export const myValidator: ValidatorFn = /* ... */;
export const myOtherValidator: ValidatorFn = /* ... */;
export function myJustAnotherValidator(/* ... */) { /* ... */ }

And you can import them like import { myValidator, myOtherValidator } from '../mypath/reactive-validators'; Or import * as ReactiveValidators from '../mypath/reactive-validators';

No module import required

0
votes

As per @dzenesiz he figured out issue, the issue was in importing syntax.

The correct import statement is import.

{ maxInputLengthValidator } from '../../validators/reactive-validators'

Notice the relative path. And, for some reason, VS Code auto import uses absolute path, the one in the error message. I fixed the path, now it works