admin管理员组

文章数量:1356733

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 -]*$/

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 -]*$/

Share Improve this question asked Apr 17, 2014 at 7:10 Green WizardGreen Wizard 3,6674 gold badges20 silver badges32 bronze badges 2
  • 1 What are special characters? – Toto Commented Apr 17, 2014 at 7:12
  • Which special characters do you want to allow ? – Pedro Lobito Commented Apr 17, 2014 at 7:29
Add a ment  | 

4 Answers 4

Reset to default 2

/[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.

According to your ment, 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.

Use negative Lookahead:

if (/^(?![\s\S]*[^\w -]+)[\s\S]*?$/im.test(subject)) {
    // Successful match
} else {
    // Match attempt failed
}

DEMO

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) «$»

~[^a-zA-z0-9 ]+~ it will matches if the String doesnot contains atleast one alphabets and numbers and spaces in it.

Demo

本文标签: javascriptregular expression to avoid only special charsStack Overflow