admin 管理员组文章数量: 1086019
I need to know if a string contains a character (one or multiple times) at any point of the string. For example with the character "&":
"&hfds" is invalid, "%$/&h&" is invalid etc.
Im doing this as part of a password validation:
function applySpecialCharacterFilter(password) {
if (password.match(/([!,%,@,#,$,^,*,?,_,~])/)) {
return 1;
} else if(password.match(/([&])/)) {
throw new Error('Das Passwort enthält unerlaubte Zeichen.');
}
return 0;
}
in the first part it checks of the password contains any of the allowed characters, and then increments the value of the validation. But then passwords containing not allowed characters can pass. With the else if im trying to catch it, but it only works if its not in a special character sequence like $%&
Thank you
Edit:
Here is the whole function:
function checkStrength(password){
var strength = 0;
var passwordMessage = $('#passwordMessage');
if (password.length == 0) {
result.removeClass();
return '';
}
if (password.length < 6) {
validPassword = false;
result.removeClass();
result.addClass('short');
return 'Too short';
} else if(password.length > 8) {
validPassword = false;
result.removeClass();
result.addClass('short');
return 'Too long';
} else {
strength += 1;
}
try {
strength += applyLowerAndUpperCaseFilter(password);
strength += applyNumbersAndCharactersFilter(password);
strength += applySpecialCharacterFilter(password);
strength += applyTwoSpecialCharacterFilter(password);
strength += applyAlphabeticalCharacterCriteria(password);
} catch(error) {
validPassword = false;
result.removeClass();
result.addClass('short');
passwordMessage.html('').append('<p>TPassword contains invalid characters!</p>');
return 'Invalid';
}
passwordMessage.html('');
if (strength <= 2) {
validPassword = false;
result.removeClass();
result.addClass('weak');
return 'Schwach';
} else if (strength <= 3 ) {
validPassword = true;
result.removeClass();
result.addClass('good');
return 'Good';
} else {
validPassword = true;
result.removeClass();
result.addClass('strong');
return 'Strong';
}
}
function applyLowerAndUpperCaseFilter(password) {
if (password.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/))
return 1;
return 0;
}
function applyNumbersAndCharactersFilter(password) {
if (password.match(/([a-zA-Z])/) && password.match(/([0-9])/))
return 1;
return 0;
}
function applySpecialCharacterFilter(password) {
if (password.match(/^([!%@#$^*?_~]+)$/)) {
return 1;
} else if(password.match(/([&])/)) {
throw new Error('Das Passwort enthält unerlaubte Zeichen.');
}
return 0;
}
function applyTwoSpecialCharacterFilter(password) {
if (password.match(/(.*[!,%,@,#,$,^,*,?,_,~].*[!,",%,@,#,$,^,*,?,_,~])/))
return 1;
else if(password.match(/([&])/))
throw new Error('Das Passwort enthält unerlaubte Zeichen.');
return 0;
}
function applyAlphabeticalCharacterCriteria(password) {
var quality = 0;
var sequences = [
'abcdefghijklmnopqrstuvwxyz',
'01234567890',
'!\"§$%/()=?'
];
var proceed = true;
for(var i=0; i<(password.length-3); i++) {
for(var index = 0; index < sequences.length; index++) {
var needle = password.substring(i, 3);
if(stripos(sequences[index], needle) != false) {
quality -= 1;
proceed = false;
}
if(proceed == false) break;
}
if(proceed == false) break;
}
return quality;
}
function stripos(f_haystack, f_needle, f_offset) {
var haystack = (f_haystack + '')
.toLowerCase();
var needle = (f_needle + '')
.toLowerCase();
var index = 0;
if ((index = haystack.indexOf(needle, f_offset)) !== -1) {
return index;
}
return false;
}
The messages and classes are for real time validation output only.
Rules:
The Password needs to be between 6 and 8 characters long.
It has to have at least 1 upper and 1 lower case character.
It has to have numbers.
It has to have at leats 1 special characters (2 give more value).
Only these special characters are allowed - _ . : , ; ! @ § $ % / = ? #
The characters should not appear in a sequence if possible, so no abc,123,!§$ etc.
I need to know if a string contains a character (one or multiple times) at any point of the string. For example with the character "&":
"&hfds" is invalid, "%$/&h&" is invalid etc.
Im doing this as part of a password validation:
function applySpecialCharacterFilter(password) {
if (password.match(/([!,%,@,#,$,^,*,?,_,~])/)) {
return 1;
} else if(password.match(/([&])/)) {
throw new Error('Das Passwort enthält unerlaubte Zeichen.');
}
return 0;
}
in the first part it checks of the password contains any of the allowed characters, and then increments the value of the validation. But then passwords containing not allowed characters can pass. With the else if im trying to catch it, but it only works if its not in a special character sequence like $%&
Thank you
Edit:
Here is the whole function:
function checkStrength(password){
var strength = 0;
var passwordMessage = $('#passwordMessage');
if (password.length == 0) {
result.removeClass();
return '';
}
if (password.length < 6) {
validPassword = false;
result.removeClass();
result.addClass('short');
return 'Too short';
} else if(password.length > 8) {
validPassword = false;
result.removeClass();
result.addClass('short');
return 'Too long';
} else {
strength += 1;
}
try {
strength += applyLowerAndUpperCaseFilter(password);
strength += applyNumbersAndCharactersFilter(password);
strength += applySpecialCharacterFilter(password);
strength += applyTwoSpecialCharacterFilter(password);
strength += applyAlphabeticalCharacterCriteria(password);
} catch(error) {
validPassword = false;
result.removeClass();
result.addClass('short');
passwordMessage.html('').append('<p>TPassword contains invalid characters!</p>');
return 'Invalid';
}
passwordMessage.html('');
if (strength <= 2) {
validPassword = false;
result.removeClass();
result.addClass('weak');
return 'Schwach';
} else if (strength <= 3 ) {
validPassword = true;
result.removeClass();
result.addClass('good');
return 'Good';
} else {
validPassword = true;
result.removeClass();
result.addClass('strong');
return 'Strong';
}
}
function applyLowerAndUpperCaseFilter(password) {
if (password.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/))
return 1;
return 0;
}
function applyNumbersAndCharactersFilter(password) {
if (password.match(/([a-zA-Z])/) && password.match(/([0-9])/))
return 1;
return 0;
}
function applySpecialCharacterFilter(password) {
if (password.match(/^([!%@#$^*?_~]+)$/)) {
return 1;
} else if(password.match(/([&])/)) {
throw new Error('Das Passwort enthält unerlaubte Zeichen.');
}
return 0;
}
function applyTwoSpecialCharacterFilter(password) {
if (password.match(/(.*[!,%,@,#,$,^,*,?,_,~].*[!,",%,@,#,$,^,*,?,_,~])/))
return 1;
else if(password.match(/([&])/))
throw new Error('Das Passwort enthält unerlaubte Zeichen.');
return 0;
}
function applyAlphabeticalCharacterCriteria(password) {
var quality = 0;
var sequences = [
'abcdefghijklmnopqrstuvwxyz',
'01234567890',
'!\"§$%/()=?'
];
var proceed = true;
for(var i=0; i<(password.length-3); i++) {
for(var index = 0; index < sequences.length; index++) {
var needle = password.substring(i, 3);
if(stripos(sequences[index], needle) != false) {
quality -= 1;
proceed = false;
}
if(proceed == false) break;
}
if(proceed == false) break;
}
return quality;
}
function stripos(f_haystack, f_needle, f_offset) {
var haystack = (f_haystack + '')
.toLowerCase();
var needle = (f_needle + '')
.toLowerCase();
var index = 0;
if ((index = haystack.indexOf(needle, f_offset)) !== -1) {
return index;
}
return false;
}
The messages and classes are for real time validation output only.
Rules:
The Password needs to be between 6 and 8 characters long.
It has to have at least 1 upper and 1 lower case character.
It has to have numbers.
It has to have at leats 1 special characters (2 give more value).
Only these special characters are allowed - _ . : , ; ! @ § $ % / = ? #
The characters should not appear in a sequence if possible, so no abc,123,!§$ etc.
- whats the rule for the invalid? – Daniel A. White Commented Jan 7, 2015 at 13:38
- only one char or multiple chars? – giammin Commented Jan 7, 2015 at 13:40
4 Answers
Reset to default 1You have to anchor the first regex and add a quantifier:
if (password.match(/^([!,%,@,#,$,^,*,?,_,~]+)$/)) {
// here ^ ^ ^
The ma is not mandatory except if you want to match it:
if (password.match(/^([!%@#$^*?_~]+)$/)) {
You can use indexOf method:
function applySpecialCharacterFilter(password) {
if (password.indexOf('&')>-1) {
throw new Error('Das Passwort enthält unerlaubte Zeichen.');
}
if (password.match(/^([!,%,@,#,$,^,*,?,_,~]+)$/)) {
return 1;
}
return 0;
}
and you need to change your Regexp according @M42 answer
Here is an extremely shortened version of the password strength algorithm:
document.querySelector(".password").addEventListener("input",ev=>{
const s=ev.target.value;
strength=+(s.length>5&&s.length<9&&!/&/.test(s)) && 1 + // length between 6 and 8 and NO '&' in it ...
+(/[a-z]/.test(s)&&/[A-Z]/.test(s)) // lower and upper case letters
+(/\d/.test(s)&&/[a-z]/i.test(s)) // letters and numbers
+/[!%@#$^*?_~]/.test(s) // at least 1 special character
+/(?:[!%@#$^*?_~].*){2,}/.test(s) // at least 2 special characters
+!s.split("").some((c,i,a)=> // no sequence of 3 characters or more
i>1 && s.charCodeAt(i)-s.charCodeAt(i-1)==1
&& s.charCodeAt(i-1)-s.charCodeAt(i-2)==1 )
console.log(`${s} has a password strength of ${strength}`);
});
<input type="text" class="password">
The console will show a number from 0 to 6 indicating the password strength of the entered password.
There is no need to test for any particular invalid character. Rather, make sure your content contains nothing but valid characters and deduce that there must be an invalid character otherwise.
function applyInvalidCharacterFilter(password) {
if (!password.match(/^[A-Za-z0-9\-_.:,;!@§\$%\/=?#]*$/)) {
// The password contains illegal characters
throw new Error('Das Passwort enthält unerlaubte Zeichen.');
}
return 0;
}
You can add the above function to your list, and remove any specific tests of whether you have the '&' character, as it would already have been caught.
Also, I would remend breaking your logic down into two steps. First, check whether the password is valid. You can treat all invalid passwords as having a strength value of zero and return an error message. Once proven valid, you can then assess the strength of a password and return a score.
本文标签: regexHow to check if string contains character at any point in javascriptStack Overflow
版权声明:本文标题:regex - How to check if string contains character at any point in javascript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://roclinux.cn/p/1744084225a2530819.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论