Reputation: 3657
I'm validating a input text box. I'm new to regexp. I want an expression which throws a validation error if all the characters of input are special characters. but it should allow special characters in the string.
-(**&^&)_) ----> invalid.
abcd-as jasd12 ----> valid.
currently validating for numbers and alphabets with /^[a-zA-Z0-9-]+[a-z A-Z 0-9 -]*$/
Upvotes: 2
Views: 8064
Reputation: 98881
Use negative Lookahead:
if (/^(?![\s\S]*[^\w -]+)[\s\S]*?$/im.test(subject)) {
// Successful match
} else {
// Match attempt failed
}
EXPLANATION:
^(?!.[^\w -]+).?$
Assert position at the beginning of a line (at beginning of the string or after a line break character) «^»
Assert that it is impossible to match the regex below starting at this position (negative lookahead) «(?!.*[^\w -]+)»
Match any single character «.*»
Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»
Match a single character NOT present in the list below «[^\w -]+»
Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
A word character (letters, digits, and underscores) «\w»
The character “ ” « »
The character “-” «-»
Match any single character «.*?»
Between zero and unlimited times, as few times as possible, expanding as needed (lazy) «*?»
Assert position at the end of a line (at the end of the string or before a line break character) «$»
Upvotes: 1
Reputation: 91375
According to your comment, special characters are !@#$%^&*()_-
, so you could use:
var regex = /^[!@#$%^&*()_-]+$/;
if (regex.test(string))
// all char are special
If you have more special char, add them in the character class.
Upvotes: 2
Reputation: 12042
~[^a-zA-z0-9 ]+~
it will matches if the String doesnot contains atleast one alphabets and numbers and spaces in it.
Upvotes: 1
Reputation: 706
/[A-Za-z0-9]/
will match positive if the string contains at least 1 letter or number, which should be the same as what you're asking. If there are NO letters or numbers, that regex will evaluate as false.
Upvotes: 2