Custom validation [Solved]

A couple of things:

  • Don’t create needless promises. getUsario() is presumably giving you one, simply chain off that. Do not make a new one.

  • DI is smart, but not smart enough to do anything with let db: VentasServicio;. db is going to be null and I suspect this is the source of your problems. Instead use a lambda like so:

class SomePage {
  registroForm: FormGroup;

  constructor(fb: FormBuilder, db: VentasServicio) {
    let isUsario = (control: FormControl) => {
      // in here, `db` is magically reliable
      return db.getUsario(control.value).then(data => data ? {} : {"is_usario": true});
    };

   this.regsitroForm = fb.group({
      'usuario': ['', Validators.required, isUsario],
    });
  }
}

If you insist on breaking it out into a separate class from the page (for reusability reasons, for example), look into how to provide deps to custom providers (any unit testing Http services example will have an example of doing this to mock HttpBackend) and use that method to inject it into the constructor of UsarioValidator.

2 Likes