Angular 2密码验证问题:如何配置大小写/数字/特殊字符规则
Got it, let's fix that password validation for you in Angular 2! You've already nailed the length check, so we just need to layer on the remaining rules using regex and Angular's built-in form validation tools.
First, we'll need a regex pattern that enforces all your requirements: at least one uppercase letter, one lowercase letter, one number, one special character, and 8-16 total characters. Here's the pattern we'll use:
^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,16}$
Breakdown of the regex:
(?=.*[a-z]): Ensures at least one lowercase letter exists(?=.*[A-Z]): Ensures at least one uppercase letter exists(?=.*\d): Ensures at least one number exists(?=.*[@$!%*?&]): Ensures at least one of the specified special characters exists (tweak this set if you need to allow more/other symbols)[A-Za-z\d@$!%*?&]{8,16}: Restricts the total length to 8-16 characters and only allows the approved character set
Now let's integrate this into your template-driven form. Here's the updated code with validation and clear error messages:
<div class="form-group"> <label>Password</label> <input class="form-control" name="password" #passwordInput="ngModel" type="password" [(ngModel)]="user.password" required minlength="8" maxlength="16" pattern="^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,16}$" > <!-- Error message block --> <div *ngIf="passwordInput.invalid && (passwordInput.dirty || passwordInput.touched)" class="text-danger"> <div *ngIf="passwordInput.errors?.['required']">Password cannot be empty</div> <div *ngIf="passwordInput.errors?.['minlength']">Password must be at least 8 characters long</div> <div *ngIf="passwordInput.errors?.['maxlength']">Password cannot exceed 16 characters</div> <div *ngIf="passwordInput.errors?.['pattern']"> Password must include at least one uppercase letter, one lowercase letter, one number, and one special character (@$!%*?&) </div> </div> </div>
If you want to clean up the template a bit, you can define the regex in your component class instead of inline:
Component class code:
import { Component } from '@angular/core'; @Component({ selector: 'app-password-form', templateUrl: './password-form.component.html' }) export class PasswordFormComponent { user = { password: '' }; // Store regex in component for cleaner template passwordValidationPattern = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,16}$/; }
Then update the input's pattern attribute in the template:
pattern="{{ passwordValidationPattern }}"
Note: If you need to allow a different set of special characters, just adjust the @$!%*?& part of the regex. For example, adding # would make that section @$!%*?&#.
内容的提问来源于stack exchange,提问作者sundeep

