0

I need to add custom validators to a form from formvalidation.service.ts
form.component.ts

myForm = this.formBuilder.group({
    name: ['', [Validators.required,]]
});

formvalidator.service.ts

passwordValidator(): ValidatorFn {
   return (control: AbstractControl): {[key: string]:any} | null => {
     const year = control.value;
     if (!/[0-9]/.test(year) || !/[A-Z]/.test(year)) {
       return { passwordPattern: true};
     }
     return null;
   }
}

I import it as FormValidator.passwordValidator(). It can't import this to the component.ts file. But when the static passwordValidator(): ValidatorFn {} it can do. but my superviser advice me to not to use static methods.

1
  • That's because if you create your function inside a class, if you want to call it you have to instance the class: new FormValidator().passwordValidator(). For me it's overkill creating a class only for this, it's probably better to create a standalone function and export it. Commented Feb 7, 2023 at 17:03

2 Answers 2

0

You need service class instance in form.component:

export class FormComponent {
  ...
  constructor(private validator: FormValidatorService) {}
  myForm = this.formBuilder.group({
    name: ['', [Validators.required, this.validator.passwordValidator]]
  });
  ...
  
}
0

You can not import as FormValidator.passwrodValidator, but you can inject the service in the constructor of your component and use

constructor(private formValidator:FormValidator){}
//and use
name:['',this.formValidator.passwordValidator]

The another option is declare the function outside the service (but in the same .ts)

export function passwordValidator(): ValidatorFn {..}

Then you can import {passwordValidator} from './services/service.ts'

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.