views:

67

answers:

1
+1  Q: 

Validate a string

I'm not that good with regular expressions...

I need a JavaScript regular expression that will do the following:

  1. The string can contain letters (upper and lower case), but not punctuations such as éàïç...
  2. The string can contain numbers (0..9) anywhere in the string, except on the first position.
  3. The string can contain underscores (_).

Valid strings:

  • foo
  • foo1
  • foo_bar
  • fooBar

Invalid strings:

  • 1foo --> number as first character
  • foo bar --> space
  • föo --> punctuation ö

Many thanks!

+8  A: 

This regex should do what you need:

/^[a-z_]+[\w]*$/i

Use it as follows:

var match = /^[a-z_]+[\w]*$/i.test(string);

Some explanation:

/      : start of JavaScript regex pattern
^      : start of string
[a-z_] : only alphabetic characters or underscore
+      : one or more
[\w]   : any word-character (aplhanumeric and the underscore)
*      : zero or more
$      : end of string
/      : end of JavaScript regex pattern
i      : case insensitive modifier

To learn more about regular expressions, you may find this site useful.

BalusC
Just needs an underscore in the [a-z]: `[a-z_]`
Infinity
Yes, if the underscore may appear anywhere, then the `[a-z]` should indeed be `[a-z_]`. Hmm, actually, you're right he didn't explicitly forbid the underscore in the front. Updated answer.
BalusC
Activist
You're welcome.
BalusC