简体   繁体   English

如何在 Angular 7 中使用数字 0-9 和字母 az 和 AZ 验证用户输入?

[英]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 AZ) and minimum length should be 8. I tried a lot, but I could not get a good solution.我正在开发一个项目,该项目必须允许数字 (0-9)、字符(a -z 和 AZ)的组合,最小长度应为 8。我尝试了很多,但找不到好的解决方案。

 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"例如:它应该是“s12sre34”

Try updating the validator Validators.pattern('(?=(?:\\d*[A-Za-z]){1,})(?=(?:[A-Za-z]*\\d){1,})[A-Za-z\\d]{8}')])尝试更新验证器Validators.pattern('(?=(?:\\d*[A-Za-z]){1,})(?=(?:[A-Za-z]*\\d){1,})[A-Za-z\\d]{8}')])

Explanation:解释:

(?=(?:\d*[A-Z]){1,})(?=(?:[A-Z]*\d){1,})[A-Za-z\d]{8}
  • (?=(?:\\d*[A-Za-z]){1,}) positive lookahead of non-capturing group matching a [digit-then-letter] pattern happening 1 or more times (?=(?:\\d*[A-Za-z]){1,})匹配 [digit-then-letter] 模式发生 1 次或多次的非捕获组的正向预测
  • (?=(?:[A-Za-z]*\\d){1,}) positive lookahead of non-capturing group matching a [letter-then-digit] pattern happening 1 or more times (?=(?:[A-Za-z]*\\d){1,})匹配 [letter-then-digit] 模式发生 1 次或多次的非捕获组的正向预测
  • [A-Za-z\\d]{8} match eight digits or letters so length is correct [A-Za-z\\d]{8}匹配八个数字或字母所以长度是正确的

  • note 1: A-Za-z can just be AZ if you ignore case注意 1:如果忽略大小写, A-Za-z可以只是AZ
  • note 2: \\d is the same as 0-9 in other examples注 2: \\d与其他示例中的0-9相同

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 };

        };

    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM