61

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?

Quicksilver
  • 2,546
  • 3
  • 23
  • 37
  • 6
    The key is to use `^` at the beginning and `+$` at the end, as the answers below have explained. `/^[a-zA-Z0-9&_\.-]+$/`. I'm pointing this out in case you missed that subtle difference. – Nathan Wall Dec 19 '12 at 06:49

7 Answers7

93

Add them to the allowed characters, but you'll need to escape some of them, such as -]/\

var pattern = /^[a-zA-Z0-9!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]*$/

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&.\-]+$/

[\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:

/^[\w&.\-]*$/
Highly Irregular
  • 38,000
  • 12
  • 52
  • 70
  • 3
    I would suggest that any list which allows all those special characters should allow spaces as well. – Abacus Dec 03 '15 at 16:59
  • 1
    Plus (+) character doesn't work with this expression – calbertts Sep 23 '16 at 15:20
  • @calbertts, do you mean where it's included in the list of characters in "var pattern..."? Which language are you using? Javascript? – Highly Irregular Sep 23 '16 at 20:19
  • @HighlyIrregular I've tried to match a string with a plus (+) with Javascript, but I've found it's not that easy, actually, I just gave up with this and made a separated validation. – calbertts Sep 23 '16 at 22:08
  • @calbertts, when the + character is not in square brackets, it needs to be escaped or it gets treated as a wildcard character. As a wildcard, it means: match 1 or more of the previous character/group-of-characters (depending on if they are wrapped in round or square brackets etc). eg In the pattern /^[\w&.\-]+$/, the + character is being used as a wildcard. – Highly Irregular Sep 24 '16 at 03:42
  • With spaces: ^[a-zA-Z0-9!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?\s]*$ – Tana Feb 28 '20 at 17:37
20

Well, why not just add them to your existing character class?

var pattern = /[a-zA-Z0-9&._-]/

If you need to check whether a string consists of nothing but those characters you have to anchor the expression as well:

var pattern = /^[a-zA-Z0-9&._-]+$/

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:

var pattern = /^[\w&.-]+$/

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 use RegExp.test() which returns a simple boolean:

if (pattern.test(qry)) {
    // qry is non-empty and only contains letters, numbers or special characters.
}

Update 2

In case I have misread the question, the below will check if all three separate conditions are met.

if (/[a-zA-Z]/.test(qry) && /[0-9]/.test(qry) && /[&._-]/.test(qry)) {
   // qry contains at least one letter, one number and one special character
}
Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
  • 4
    +1. It might be worth mentioning to use `test` instead of `match`, since you don't really need the matches to be found. This could help performance, readability, and might help the asker learn something new. – Nathan Wall Dec 19 '12 at 06:40
  • 1
    Also, no slash after the `i`. `/[a-z]/i/` should be `/[a-z]/i`. – Nathan Wall Dec 19 '12 at 06:41
16

Try this regex:

/^[\w&.-]+$/

Also you can use test.

if ( pattern.test( qry ) ) {
  // valid
}
elclanrs
  • 92,861
  • 21
  • 134
  • 171
2
let pattern = /^(?=.*[0-9])(?=.*[!@#$%^&*])(?=.*[a-z])(?=.*[A-Z])[a-zA-Z0-9!@#$%^&*]{6,16}$/;

//following will give you the result as true(if the password contains Capital, small letter, number and special character) or false based on the string format

let reee =pattern .test("helLo123@");   //true as it contains all the above
Amrutha VS
  • 144
  • 1
  • 1
  • 10
0

Try this RegEx: Matching special charecters which we use in paragraphs and alphabets

   Javascript : /^[a-zA-Z]+(([\'\,\.\-_ \/)(:][a-zA-Z_ ])?[a-zA-Z_ .]*)*$/.test(str)

                .test(str) returns boolean value if matched true and not matched false

            c# :  ^[a-zA-Z]+(([\'\,\.\-_ \/)(:][a-zA-Z_ ])?[a-zA-Z_ .]*)*$
0

I tried a bunch of these but none of them worked for all of my tests. So I found this:

^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z0-9])(?!.*\s).{8,15}$

from this source: https://www.w3resource.com/javascript/form/password-validation.php

Aaron
  • 3,249
  • 4
  • 35
  • 51
0

Here you can match with special char:

function containsSpecialChars(str) {
  const specialChars = /[`!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?~]/;
  return specialChars.test(str);
}

console.log(containsSpecialChars('hello!')); // ️ true
console.log(containsSpecialChars('abc')); // ️ false
console.log(containsSpecialChars('one two')); // ️ false
Shubham Verma
  • 8,783
  • 6
  • 58
  • 79