如何使用Angular 5 Validator Pattern验证密码强度 [英] How to validate password strength with Angular 5 Validator Pattern
问题描述
我需要验证密码输入表单字段的强度.
要求是:
-至少一个小写字符
-至少一个大写字符
-至少一个号码
(无论顺序如何)
I need to validate the strength of a password input form field.
The requirements are:
- at least one lowercase char
- at least one uppercase char
- at least one number
(no matter the order)
我到目前为止搜索和尝试过的内容如下,结果不一致.
似乎可以验证正则表达式验证的顺序.
我需要的只是检查是否存在至少一种字符类型".
谢谢
What I have searched and tried so far goes below, the results are inconsistent.
It seems to validate the order of the regex validation.
What I need is to just check if at least one of the char "types" are present.
Thanks
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'signup',
templateUrl: './signup.component.html',
styleUrls: ['./signup.component.scss']
})
export class SignupComponent {
form: FormGroup;
constructor() {
this.init();
}
init() {
this.form = this.fb.group({
name: ['', [Validators.required]],
email: ['', [Validators.required, Validators.email],
password: ['', [
Validators.required,
Validators.pattern('((?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,30})')
]]
});
}
}
推荐答案
我使用Angular的内置模式验证器对此进行了测试,并提出了以下检查条件:
I took a stab at this with Angular's built-in pattern validator and was able to come up with the following that checks for:
- 长度至少8个字符
- 小写字母
- 大写字母
- 数字
-
特殊字符
- At least 8 characters in length
- Lowercase letters
- Uppercase letters
- Numbers
Special characters
password: [
'',
[
Validators.required,
Validators.pattern('(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[$@$!%*?&])[A-Za-z\d$@$!%*?&].{8,}')
]
]
我要补充一点,我绝不是正则表达式专家.对于与OP密切相关的案例,这就是对我有用的方法.也许会帮助别人. Mozilla的文档为解决这一问题提供了很大帮助,特别是写作正则表达式模式部分.
I'll add that I'm by no means a regex expert. This is simply what worked for me for a closely related case to the OP. Maybe it will help someone else. Mozilla's documentation helped a lot in figuring this out, specifically the Writing a regular expression pattern section.
这篇关于如何使用Angular 5 Validator Pattern验证密码强度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!