您使用角度2作为密码字段我必须设置“密码应至少有1个大写,1个小写,1个数字,1个特殊字符,最少8个字符,最多16个字符”
因为我完成了“最少8个字符,最多16个字符”。
但我无法设置剩下的最少1个大写,1个小写,1个数字,1个特殊字符。
<div class ="form-group">
<label> Password </label>
<input class ="form-control" name ="password" #password="ngModel" [(ngModel)] = "angulaService.selectedAngula.password"
placeholder="password" minlength="8" maxlength="16" >
<div class="form-control-feedback"
*ngIf="password.errors && (password.dirty || password.touched)">
<p *ngIf="password.errors.required">Password is required</p>
<p *ngIf="password.errors.minlength">Password must be min 8 characters long</p>
</div>
<div class="form-control-feedback"
*ngIf="password.errors && (password.dirty || password.touched)">
<p *ngIf="password.errors.required">Password is required</p>
<p *ngIf="password.errors.maxlength">Password should not be greater than 16 characters long</p>
</div>
</div>
请帮助我
先谢谢
答案 0 :(得分:1)
大写验证器示例:
import { Directive } from '@angular/core';
import {NG_VALIDATORS, AbstractControl, ValidationErrors, Validator} from '@angular/forms';
@Directive({
selector: '[uppercaseValidator]',
providers: [{provide: NG_VALIDATORS, useExisting: UppercaseValidatorDirective, multi: true}]
})
export class UppercaseValidatorDirective implements Validator {
validate(control: AbstractControl): ValidationErrors | null {
const value = control.value
return /[A-Z]/.test(value) ? null : { uppercase: 'Must contain at least one upper case character'}
}
}
用法:
app.component.html
<form>
<input uppercaseValidator [(ngModel)]="uppercase" #uppercaseCtrl="ngModel" name="uppercase"/>
<div *ngIf="uppercaseCtrl.hasError('uppercase')">At least one character must be uppercased</div>
</form>
app.component.ts
<form>
<input uppercaseValidator [(ngModel)]="uppercase" #uppercaseCtrl="ngModel" name="uppercase"/>
<div *ngIf="uppercaseCtrl.hasError('uppercase')">At least one character must be uppercased</div>
</form>
按照创建自定义验证指令的相同步骤创建其他验证器。您只需要更改正则表达式和错误消息。您可以使用以下正则表达式:
/[A-Z]/
/[a-z]/
/[0-9]/
答案 1 :(得分:0)
最好使用Regex,
^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$@$!%*?&])[A-Za-z\d$@$!%*?&]
(你已经检查了最小长度和最大长度,因此不需要在正则表达式中设置长度限制,但你仍然可以通过正则表达式来实现。虽然我建议将两个错误分开。)