【发布时间】:2018-11-12 06:14:50
【问题描述】:
在下面的代码中,我传递了一个包含密码的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'
}
这个前向查找不应该匹配(?=.*[!@#$%^&*()_+}{":'?&gt.<,])
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
【问题讨论】:
标签: regex angular6 karma-jasmine