Vijikumar M
Vijikumar M

Reputation: 3764

How to allow only special characters as input?

How can I check if an entered input only has special characters? I tried the following, but its not working:

/^[\p{L}\s\p{N}._@?¿!¡€-]+$/

Upvotes: 0

Views: 118

Answers (4)

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

To check whether an input contains only digits and letters from any alphabet, one might use \p{Alnum} matcher

▶ '¡Hello!' !~ /^\p{Alnum}+$/
#=> false
▶ 'Hello' !~ /^\p{Alnum}+$/
#=> true
▶ '¿Привет?' !~ /^\p{Alnum}+$/
#=> false
▶ 'Привет' !~ /^\p{Alnum}+$/
#=> true

That said, to check for non-alphanumerics:

▶ not '!@#$%^&()!@' !~ /^[^\p{Alnum}]+$/
#=> true
▶ not 'a!@#$%^&()!@' !~ /^[^\p{Alnum}]+$/
#=> false

Upvotes: 0

sawa
sawa

Reputation: 168081

"!@#$%^&()!@" !~ /\w/  # => true
"!a@#$%^&()!@" !~ /\w/ # => false

Upvotes: 2

Ján Stibila
Ján Stibila

Reputation: 637

This will match anything that contains only non-word characters (anything but alpha-numeric)

/^[\W]+$/

//edit it also doesn't match _

Upvotes: 0

hek2mgl
hek2mgl

Reputation: 157947

What about this?:

/^[^A-Za-z0-9]+$/

The pattern matches from the beginning to the end of the string and allows one or more characters which are not a letter or a number.

Upvotes: 1

Related Questions