如何编写含大小写及数字校验的Angular密码自定义验证器?
Angular Custom Password Validator: Require Uppercase, Lowercase, and Number
Got it, let's fix up that directive to add the password validation logic you need. The goal is to ensure the password has at least one uppercase letter, one lowercase letter, and one number—here's the complete, working implementation:
import { Directive, forwardRef } from '@angular/core'; import { NG_VALIDATORS, Validator, AbstractControl } from '@angular/forms'; @Directive({ selector: '[checkPattern][formControlName],[checkPattern][formControl],[checkPattern][ngModel]', providers: [ { provide: NG_VALIDATORS, useExisting: forwardRef(() => PatternValidator), multi: true } ] }) export class PatternValidator implements Validator { constructor() {} validate(control: AbstractControl): { [key: string]: any } | null { // Skip validation if control is empty (let required validator handle empty checks) if (!control.value) { return null; } // Regex to enforce at least one uppercase, one lowercase, one number const passwordPattern = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).+$/; // Test the input value against our pattern const isValid = passwordPattern.test(control.value); // Return error object if invalid, null if validation passes return isValid ? null : { invalidPattern: true }; } }
Key Details:
- Regex Breakdown:
(?=.*[a-z]): Ensures the password contains at least one lowercase letter(?=.*[A-Z]): Ensures at least one uppercase letter is present(?=.*\d): Checks for at least one numeric digit.+: Matches any character sequence (so we avoid validating empty strings here)
- Validation Flow: We first skip validation if the input is empty (you can pair this with Angular's built-in
requiredvalidator if you need to enforce non-empty passwords). If the value exists, we test it against our regex—returning aninvalidPatternerror if it fails, ornullif it meets all requirements.
How to Use It:
Add the checkPattern attribute to your password input in the template:
<!-- Reactive Forms Example --> <input type="password" formControlName="password" checkPattern> <!-- Template-Driven Forms Example --> <input type="password" ngModel name="password" checkPattern>
Then display an error message when validation fails:
<div *ngIf="passwordForm.get('password')?.hasError('invalidPattern')"> Password must include at least one uppercase letter, one lowercase letter, and one number. </div>
Don't forget to declare the PatternValidator in your Angular module's declarations array so it's available to your components!
内容的提问来源于stack exchange,提问作者Abhishek Saha
相关产品推荐
相关产品推荐

