Search code examples
angularvmware-clarity

VM Clarity - Unable to use custom validator with clr-control-error


How can i display error message from custom validator using clr-control-error? I have a custom validator to confirm password matching. Other validators like required, minlength and maxlength are working well. I'm using the latest version of clarity.

signup.ts

  ngOnInit() {
    this.createSignUpForm();
  }

  createSignUpForm() {
    this.signUpForm = this.fb.group({
      password: ['', [
        Validators.required,
        Validators.minLength(4),
        Validators.maxLength(12)
      ]],
      confirmPassword: ['', Validators.required]
    }, { validator: this.passwordMatchValidator });
  }

  passwordMatchValidator(g: FormGroup) {
    return g.get('password').value === g.get('confirmPassword').value ? null 
     : {'mismatch' : true };
  }

signup.html

        <clr-password-container>
            <label>Password</label>
            <input clrPassword formControlName="password"  />
            <clr-control-error *clrIfError="'required'">This password is required!</clr-control-error>
            <clr-control-error *clrIfError="'minlength'">It must be at least 4 characters!</clr-control-error>
            <clr-control-error *clrIfError="'maxlength'">It must be less than 12 characters!</clr-control-error>
        </clr-password-container>
        <clr-password-container>
           <label> Confirm Password</label>
           <input clrPassword formControlName="confirmPassword"/>
           <clr-control-error *clrIfError="'required'">Confirm Password is required!</clr-control-error>
           <clr-control-error *clrIfError="'mismatch'">Password Confirmation must match password</clr-control-error>
        </clr-password-container>

Solution

  • You're putting the validator at the form level and not at the form control level, which means it will never trigger for that control. I've reorganized your example into something that works as you wish with a custom validator on the confirmPassword control.

    https://stackblitz.com/edit/clarity-password-confirm-validator?file=src/app/app.component.html