I am trying to validate a string, that should contain letters numbers and special characters &-._
only. For that I tried with a regular expression.
var pattern = /[a-zA-Z0-9&_\.-]/
var qry = 'abc&*';
if(qry.match(pattern)) {
alert('valid');
}
else{
alert('invalid');
}
While using the above code, the string abc&*
is valid. But my requirement is to show this invalid. ie Whenever a character other than a letter, a number or special characters &-._
comes, the string should evaluate as invalid. How can I do that with a regex?
Try this regex:
Also you can use
test
.Well, why not just add them to your existing character class?
If you need to check whether a string consists of nothing but those characters you have to anchor the expression as well:
The added
^
and$
match the beginning and end of the string respectively.Testing for letters, numbers or underscore can be done with
\w
which shortens your expression:As mentioned in the comment from Nathan, if you're not using the results from
.match()
(it returns an array with what has been matched), it's better to useRegExp.test()
which returns a simple boolean:Update 2
In case I have misread the question, the below will check if all three separate conditions are met.
let pattern = /^(?=.[0-9])(?=.[!@#$%^&])(?=.[a-z])(?=.[A-Z])[a-zA-Z0-9!@#$%^&]{6,16}$/; let reee =pattern .test("helLo123@"); //true
Try this RegEx: Matching special charecters which we use in paragraphs and alphabets
Add them to the allowed characters, but you'll need to escape some of them, such as -]/\
That way you can remove any individual character you want to disallow.
Also, you want to include the start and end of string placemarkers ^ and $
Update:
As elclanrs understood (and the rest of us didn't, initially), the only special characters needing to be allowed in the pattern are &-._
[\w] is the same as [a-zA-Z0-9_]
Though the dash doesn't need escaping when it's at the start or end of the list, I prefer to do it in case other characters are added. Additionally, the + means you need at least one of the listed characters. If zero is ok (ie an empty value), then replace it with a * instead: