[Fixed] validation service isssue in formcontrol default value as null

Issue

Am using Angular 10 ..Password validator Service

 static password(control: AbstractControl) {

        // {6,100}           - Assert password is between 6 and 100 characters
        // (?=.*[0-9])       - Assert a string has at least one number
        if (control.value.match(/^(?=.*[0-9])[[email protected]#$%^&*]{6,100}$/)) {
          return null;
        } else {
          return { invalidPassword: true };
        }
      }

Working Code

this.loginForm = this.formBuilder.group({
      username:'' ,
      password: ['', [ValidationService.password]]
    });

Not working Code :

  this.loginForm = this.formBuilder.group({
          username:'' ,
          password: [null, [ValidationService.password]]
        });

I Have used null…But now getting below error while loading login form

How to fix that ..Please let me know

enter image description here

EDIT :

HTML

          <div class="input-group mb-4">
            <div class="input-group-prepend">
              <span class="input-group-text"><i class="icon-lock"></i></span>
            </div>
            <input type="password" class="form-control" placeholder="Password" autocomplete="current-password"
              formControlName="password" required>
          </div>
          <div class="form-group row">
            <div class="col-md-9">
           
              <ar-validation-message [control]="loginForm.controls.password"></ar-validation-message>
            </div>
          </div>

Solution

add safe navigation operator ?. here

if (control.value?.match(...

with this code null value will pass through and won’t trigger an error

Leave a Reply

(*) Required, Your email will not be published