Search code examples
angularvalidationangular-reactive-formsstatic-methodsangular-services

Form Validation from service.ts Angular


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.


Solution

  • 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]]
      });
      ...
      
    }