Search code examples
javascriptangularangular7

How to validate user input with numbers 0-9 and letters a-z and A-Z in Angular 7?


I am working on a project that must allow combination of numbers (0-9), characters (a -z and A-Z) and minimum length should be 8. I tried a lot, but I could not get a good solution.

 ngOnInit() {
    this.newPasswordFormGroup = this.formBuilder.group({
      newPassword: ['', Validators.compose([Validators.required,
        Validators.minLength(8),
        Validators.pattern('^A-Za-z0-9')])],
      confirmPassword: ['', Validators.required],
    }, {
      validator: MustMatch('newPassword', 'confirmPassword')
  });
  }


<form [formGroup]="newPasswordFormGroup" role="form" (ngSubmit)="onSubmitPassword()">
                <div class="form-group text-left">
                    <input type="password" [ngClass]="{ 'is-invalid': submitted && f.newPassword.errors }" formControlName="newPassword" class="form-control input-underline input-lg textBox" id="newPassword" placeholder="Enter new password" />
                    <div *ngIf="submitted && f.newPassword.errors" class="invalid-feedback">
                        <div *ngIf="f.newPassword.errors.required">New password is required</div>
                    </div>
                    <div *ngIf="submitted && f.newPassword.errors" class="invalid-feedback">
                        <div *ngIf="f.newPassword.errors.pattern">#Password should be a minimum of 8 characters and contain a combination of letters and numbers</div>
                    </div>
                    <div *ngIf="submitted && f.newPassword.errors" class="invalid-feedback">
                        <div *ngIf="f.newPassword.errors.minlength">Password should be a minimum of 8 characters</div>
                    </div>
                </div>
                <div class="form-group text-left">
                    <input type="password" [ngClass]="{ 'is-invalid': submitted && f.confirmPassword.errors }" formControlName="confirmPassword" class="form-control input-underline input-lg textBox" id="confirmPassword" placeholder="Enter confirm password" />
                    <div *ngIf="submitted && f.confirmPassword.errors" class="invalid-feedback">
                        <div *ngIf="f.confirmPassword.errors.required">Confirm password is required</div>
                    </div>
                    <div *ngIf="submitted && f.confirmPassword.errors" class="invalid-feedback">
                        <div *ngIf="f.confirmPassword.errors.mustMatch">Passwords must match</div>
                    </div>
                </div>
                <div class="password-btn">
                    <button type="submit" [disabled]="isDisabled" class="btn btn-primary submit-btn"> Submit </button>
                </div>
            </form>

Ex: It should be "s12sre34"


Solution

  • I did like this. it worked for me.

    ngOnInit() {
        this.newPasswordFormGroup = this.formBuilder.group({
          newPassword: ['', Validators.compose([Validators.required,
            Validators.minLength(8),
            CustomValidator.findCombinationLettersAndNumbers()])],
          confirmPassword: ['', Validators.required],
        }, {
          validator: MustMatch('newPassword', 'confirmPassword')
      });
      }
    
    
     import { AbstractControl, ValidatorFn } from '@angular/forms';
    
     export class CustomValidator {
    
    
        public static findCombinationLettersAndNumbers(): ValidatorFn {
    
            return (c: AbstractControl): { [key: string]: boolean } | null => {
                // console.log('val:', c.value);
    
                let isDigit = false;
                let isCapsOrSmallLetter = false;
                // let isSmallLetter = false;
                let isSpecialChar = false;
                if ((!/\d/.test(c.value))) {
                    // console.log('password must contain digits');
                    isDigit = false;
                } else {
                    isDigit = true;
                }
                if (!/[A-Za-z]/.test(c.value)) {
                    // console.log('password must contain uppercase letter');
                    isCapsOrSmallLetter = false;
                } else {
                    isCapsOrSmallLetter = true;
                }
                // if (!/[a-z]/.test(c.value)) {
                //     console.log('password must contain lowercase letter');
                //     isSmallLetter = false;
                // } else {
                //     isSmallLetter = true;
                // }
    
                if (!/[ !@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/.test(c.value)) {
                    // console.log('password must contain special character');
                    isSpecialChar = true;
                }
    
                if (isDigit && isCapsOrSmallLetter && isSpecialChar === true) {
                    // null is required here. otherwise form wonot submit.
                    return null;
                }
                return { passwordval: true };
    
            };
    
        }
    
    }