admin管理员组文章数量:1327665
I'm trying to create a Regex test in JavaScript that will test a string to contain any of these characters:
!$%^&*()_+|~-=`{}[]:";'<>?,./
More Info If You're Interested :)
It's for a pretty cool password change application I'm working on. In case you're interested here's the rest of the code.
I have a table that lists password requirements and as end-users types the new password, it will test an array of Regexes and place a checkmark in the corresponding table row if it... checks out :) I just need to add this one in place of the 4th item in the validation
array.
var validate = function(password){
valid = true;
var validation = [
RegExp(/[a-z]/).test(password), RegExp(/[A-Z]/).test(password), RegExp(/\d/).test(password),
RegExp(/\W|_/).test(password), !RegExp(/\s/).test(password), !RegExp("12345678").test(password),
!RegExp($('#txtUsername').val()).test(password), !RegExp("cisco").test(password),
!RegExp(/([a-z]|[0-9])\1\1\1/).test(password), (password.length > 7)
]
$.each(validation, function(i){
if(this)
$('.form table tr').eq(i+1).attr('class', 'check');
else{
$('.form table tr').eq(i+1).attr('class', '');
valid = false
}
});
return(valid);
}
Yes, there's also corresponding server-side validation!
I'm trying to create a Regex test in JavaScript that will test a string to contain any of these characters:
!$%^&*()_+|~-=`{}[]:";'<>?,./
More Info If You're Interested :)
It's for a pretty cool password change application I'm working on. In case you're interested here's the rest of the code.
I have a table that lists password requirements and as end-users types the new password, it will test an array of Regexes and place a checkmark in the corresponding table row if it... checks out :) I just need to add this one in place of the 4th item in the validation
array.
var validate = function(password){
valid = true;
var validation = [
RegExp(/[a-z]/).test(password), RegExp(/[A-Z]/).test(password), RegExp(/\d/).test(password),
RegExp(/\W|_/).test(password), !RegExp(/\s/).test(password), !RegExp("12345678").test(password),
!RegExp($('#txtUsername').val()).test(password), !RegExp("cisco").test(password),
!RegExp(/([a-z]|[0-9])\1\1\1/).test(password), (password.length > 7)
]
$.each(validation, function(i){
if(this)
$('.form table tr').eq(i+1).attr('class', 'check');
else{
$('.form table tr').eq(i+1).attr('class', '');
valid = false
}
});
return(valid);
}
Yes, there's also corresponding server-side validation!
Share Improve this question edited Sep 17, 2016 at 20:58 pixelbobby asked Dec 2, 2011 at 16:38 pixelbobbypixelbobby 4,4405 gold badges31 silver badges50 bronze badges 4 |7 Answers
Reset to default 203The regular expression for this is really simple. Just use a character class. The hyphen is a special character in character classes, so it needs to be first:
/[-!$%^&*()_+|~=`{}\[\]:";'<>?,.\/]/
You also need to escape the other regular expression metacharacters.
Edit: The hyphen is special because it can be used to represent a range of characters. This same character class can be simplified with ranges to this:
/[$-/:-?{-~!"^_`\[\]]/
There are three ranges. '$' to '/', ':' to '?', and '{' to '~'. the last string of characters can't be represented more simply with a range: !"^_`[].
Use an ACSII table to find ranges for character classes.
Answer
/[\W\S_]/
Explanation
This creates a character class removing the word characters, space characters, and adding back the underscore character (as underscore is a "word" character). All that is left is the special characters. Capital letters represent the negation of their lowercase counterparts.
\W
will select all non "word" characters equivalent to [^a-zA-Z0-9_]
\S
will select all non "whitespace" characters equivalent to [ \t\n\r\f\v]
_
will select "_" because we negate it when using the \W
and need to add it back in
The most simple and shortest way to accomplish this:
/[^\p{L}\d\s@#]/u
Explanation
[^...]
Match a single character not present in the list below
\p{L}
=> matches any kind of letter from any language\d
=> matches a digit zero through nine\s
=> matches any kind of invisible character@#
=>@
and#
characters
Don't forget to pass the u
(unicode) flag.
A simple way to achieve this is the negative set [^\w\s]. This essentially catches:
- Anything that is not an alphanumeric character (letters and numbers)
- Anything that is not a space, tab, or line break (collectively referred to as whitespace)
For some reason [\W\S] does not work the same way, it doesn't do any filtering. A comment by Zael on one of the answers provides something of an explanation.
// The string must contain at least one special character, escaping reserved RegEx characters to avoid conflict
const hasSpecial = password => {
const specialReg = new RegExp(
'^(?=.*[!@#$%^&*"\\[\\]\\{\\}<>/\\(\\)=\\\\\\-_´+`~\\:;,\\.€\\|])',
);
return specialReg.test(password);
};
to build upon @jeff-hillman answer, this is the complete version
/[\\@#$-/:-?{-~!"^_`\[\]]/
Tests
function noSpecialChars(str) {
const match = str.match(/[\\@#$-/:-?{-~!"^_`\[\]]/)
if (!match) return
throw new Error("got unsupported characters: " + match[0])
}
// prettier-ignore
const symbols = ["!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "-", "_", "+", "=", ".", ":", ";", "|","~","`","{","}","[","]","\"","'","<",">","?","/", "\\"]
symbols.forEach((s) => {
it(`validates no symbol ${s}`, async () => {
expect(() => {
noSpecialChars(s)
}).toThrow();
})
})
How about (?=\W_)(?=\S).
? It checks that the character matched by the .
is not a word character (however _
is allowed) and that it's not whitespace.
Note: as @Casimir et Hippolyte pointed out in another comment, this will also match characters like é and such. If you don't expect such characters then this is a working solution.
本文标签: javascriptRegex to Match Symbols amp*()quot39ltgtStack Overflow
版权声明:本文标题:javascript - Regex to Match Symbols: !$%^&*()_+|~-=`{}[]:";'<>?,. - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736818761a1954197.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
.addClass("check")
and.removeClass("check")
? And seeingif (someBoolean == true)
in code always makes me cringe. Just doif (someBoolean)
. Or, better yet, just do$(".form table tr").eq(i+1).toggleClass("check", !!this); valid = valid && !!this;
. – gilly3 Commented Dec 2, 2011 at 16:46