0

I have created a custom validator in which I want to check password confirmation if it is valid:

  static cannotContainSpace(control: AbstractControl) : ValidationErrors | null{
    console.log('----- control', control.get('password'));
    console.log('----- control', control.get('passwordConfirmation'));
    if((control.value as string).indexOf(' ') >= 0){
      return {cannotContainSpace : true}
    }
      return null;
  }

Can you tell me why in those console logs I get all the time null values? My form was build by reactive form and looks like:

 form = new FormGroup({
    login: new FormControl('', [Validators.required, Validators.email]),
    password: new FormControl('',
      [
        Validators.required,
        Validators.minLength(3),
        PasswordValidators.cannotContainSpace
      ]),
    passwordConfirmation: new FormControl('', [Validators.required])
  });

enter image description here

bielas
  • 672
  • 2
  • 12
  • 29

2 Answers2

0

Because you are already having the control for password. So there is not point in looking for control.get(). If you use control.value instead you will see the present value for password control. And no value for passwordConfirmation as the validator is not registered under that control.

amal
  • 3,140
  • 1
  • 13
  • 20
  • Ok I have added the password validator to passwordConfirmation filed and still not working – bielas Sep 25 '17 at 17:50
  • Could you show your updated code? If you are still using control.get() it may not work. Try and see what you get for just console.log(control) and go from there. – amal Sep 25 '17 at 17:52
0

I localize the bug - it should looks like:

  form = new FormGroup({
    login: new FormControl('', [Validators.required, Validators.email]),
    password: new FormControl('',
      [
        Validators.required,
        Validators.minLength(3),
        PasswordValidators.cannotContainSpace
      ]),
    passwordConfirmation: new FormControl('', [Validators.required])
  }, PasswordValidators.cannotContainSpace);

We need to add a validator generally to the form, not to the excatly one FormControl

bielas
  • 672
  • 2
  • 12
  • 29
  • Okay so you wanted to do custom validation involving more than one controls, is that the idea? Also, did this solve your issue? – amal Sep 25 '17 at 18:47
  • Okay, didn't get this was what you were looking for from the way you posted the question. I answered a similar question before. Hope [this](https://stackoverflow.com/a/46183057/5260710) helps. – amal Sep 25 '17 at 18:49