在下面的代码中,我传递了一个包含密码的FormControl。我期望当密码为aA1[11]时,RegExp.test方法应该返回false,但它返回true!为什么我的代码返回null而不是错误对象{ validatePassword: { valid: false, message: 'password must contain 1 small-case letter [a-z], 1 capital letter [A-Z], 1 digit[0-9], 1 special character and the length should be between 6-10 characters' }
如果这个向前查找不能匹配(?=.*[!@#$%^&*()_+}{":'?>.<,])
validatePassword(control: FormControl) {
let password: string = control.value;
/* So the rule for password is
6-10 length
contains a digit
contains a lower case alphabet
contains an upper case alphabet
contains one more special character from the list !@#$%^&*()_+}{":;'?/>.<,
does not contain space
*/
let REG_EXP = new RegExp('(?=^.{6,10}$)(?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%^&*()_+}{":\'?>.<,])(?!.*\\s).*$');
/*RegExp's test method returns true if it finds a match, otherwise it returns false*/
console.log('password: ',password);
console.log('test result ',(REG_EXP.test(password)));
return (REG_EXP.test(password)) ? null : {
validatePassword: { //check the class ShowErrorsComponent to see how validatePassword is used.
valid: false,
message: 'password must contain 1 small-case letter [a-z], 1 capital letter [A-Z], 1 digit[0-9], 1 special character and the length should be between 6-10 characters'
}
}
}我从我的Karma测试用例中调用上面的函数
fit('A password of length between 6-10 characters and containing at least 1 digit, at least 1 lowercase letter, at least 1 upper case ' +
'letter and but NOT at least 1 special character from the list !@#$%^&*()_+}{":;\'?/>.<, shall NOT be accepted',
inject([HttpClient,HttpTestingController],(httpClient:HttpClient)=>{
let helper = new HelperService(loaderService,httpClient);
let passwordField = new FormControl();
let password = 'aA1[11]';
passwordField.setValue(password);
let result = helper.validatePassword(passwordField);
expect(result).toEqual(expectedErrorResponse);
}));我在控制台中看到的输出是
password: aA1[11]
test result true发布于 2018-11-12 15:26:13
您可以使用以下代码来验证密码-
validatePassword(control: FormControl) {
let password: string = control.value;
let REG_EXP = /^(?=.*\d)(?=.*[#$@!%&*?])[A-Za-z\d#$@!%&*?]{6,10}$/i; // modify as per your requirement, currently it accept atleast 1 character,1 special character,1 [0-9] number, length between 6 to 10.
if(!REG_EXP.test(password)) {
return { 'validatePassword': { //check the class ShowErrorsComponent to see how validatePassword is used.
'valid': false,
'message': 'password must contain 1 small-case letter [a-z], 1 capital letter [A-Z], 1 digit[0-9], 1 special character and the length should be between 6-10 characters'
}
}
}
}发布于 2018-11-13 06:29:55
问题出在regex上。我将&更改为&,将"更改为",将>更改为>,将<更改为<。似乎在我的代码(angular)中,&后面的字母是逐字处理的。因此,aA1[11]中的a与&中的a相匹配
https://stackoverflow.com/questions/53256757
复制相似问题