kthornbloom
kthornbloom

Reputation: 3720

Javascript RegExp for special characters ONLY

I'm building a real-time password validator. I need to check that at least one of these special characters is present: !@#$%^&*()+

I've seen other questions that also involve alpha characters and numbers, but I need to check just for the special characters. This is what I have so far, which kind of works, but stops working when I go back and edit a character in the middle of the text.

Shortened Code:

$('#account-password').on('input', function () {
    var pass = $(this).val(),
    special = /^[\!@\#\$\%\^&\*\(\)\+]+$/

   // Special Character Check
    if ($(this).val().match(special)) {
        // OK
    } else {
        //Not OK
    }

});

Full Code: http://jsfiddle.net/kthornbloom/jodbu3ta/

What is the correct way to write the regexp for special characters only?

Upvotes: 2

Views: 81

Answers (1)

anubhava
anubhava

Reputation: 784958

To check for at least one of those special character this regex will be suffice:

special = /[!@#$%^&*()+]/

Your regex: /^[\!@\#\$\%\^&\*\(\)\+]+$/ will only match when all of the input characters are made of these special characters.

PS: Inside character class you don't need to escape these special characters.

Upvotes: 1

Related Questions