【问题标题】:How to validate user input with numbers 0-9 and letters a-z and A-Z in Angular 7?如何在 Angular 7 中使用数字 0-9 和字母 a-z 和 A-Z 验证用户输入?
【发布时间】:2019-05-24 10:16:57
【问题描述】:

我正在做一个项目,该项目必须允许数字 (0-9)、字符 (a -z 和 A-Z) 的组合,并且最小长度应为 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>

例如: 应该是“s12sre34”

【问题讨论】:

  • Pattern 应该是^[a-zA-Z0-9]{8,}$,意思是“字母和数字,至少八次,从头到尾”
  • 我正在尝试这种模式
  • 如果我输入 12345678,它接受,我需要数字和字母的组合。它应该是“s12sre34”
  • must allow combination of numbers(0-9), characters(a -z and A-Z) and Minimum length should be 8。下次再具体点……无论如何,您可以使用negative lookaheads 来实现。

标签: javascript angular angular7


【解决方案1】:

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

解释:

(?=(?:\d*[A-Z]){1,})(?=(?:[A-Z]*\d){1,})[A-Za-z\d]{8}
  • (?=(?:\d*[A-Za-z]){1,}) 匹配发生 1 次或多次 [digit-then-letter] 模式的非捕获组的正向前瞻
  • (?=(?:[A-Za-z]*\d){1,}) 匹配发生 1 次或多次 [letter-then-digit] 模式的非捕获组的正向前瞻
  • [A-Za-z\d]{8} 匹配八位数字或字母,因此长度正确

  • 注 1: 如果忽略大小写,A-Za-z 可以只是 A-Z
  • 注意 2: \d 与其他示例中的 0-9 相同

【讨论】:

  • 你能解释一下吗?我应该如何输入?
  • 你有Validators.pattern('^A-Za-z0-9'),你可以用Validators.pattern('(?=(?:\d*[A-Za-z]){1,})(?=(?:[A-Za-z]*\d){1,})[A-Za-z\d]{8}')])替换它
  • 我在文本框中输入了内容。 “ii89ii898kk89”。它在 Angular 7 中不起作用。你能帮我吗?
【解决方案2】:

我确实喜欢这个。它对我有用。

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

        };

    }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-25
    • 2021-08-27
    • 1970-01-01
    • 1970-01-01
    • 2023-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多