-1

I can validate this rule using plain Javascript. But I would prefer to do it using RegEx. I tried this (and other variations) but am not too confident:

  regEx = /^[A-Z]([a-z]|[A-Z]){1,19}$/;

Test cases did go through. Is this the right way or is there a better approach?

Sunny
  • 9,245
  • 10
  • 49
  • 79
  • 2
    If there's nothing wrong with the code, or you're not having problems, you might want http://codereview.stackexchange.com/ instead. – Andy Nov 19 '15 at 09:41
  • 1
    looks good, you can save 3 character: regEx = /^[A-Z]([a-zA-Z]){1,19}$/; – Stasik Nov 19 '15 at 09:42
  • Use `regEx = /^[A-Z][a-zA-Z]{1,19}$/;`. IMHO, if you are not confident in regex, do not use it. If something can be achieved without regex, do not use regex. – Wiktor Stribiżew Nov 19 '15 at 09:42
  • 1
    @Aaron: wrong, read this http://stackoverflow.com/questions/1658844/is-the-regular-expression-a-z-valid-and-if-yes-then-is-it-the-same-as-a-za-z [A-z] is also wrong – Stasik Nov 19 '15 at 09:44

1 Answers1

1

You may need a tool for build your regEx like https://regex101.com

What do you want to match exactly ?

Your regex match the following string: - Start by a character between [A-Z] => only alphabetical upper case - 1 to 19 alphabetical character either upper or lower case

So your string length is between 2 and 20 characters.

You could simply your regExp by

regEx = /^[A-Z][a-zA-Z]{1,19}$/;

If you want no min length, mean that empty string match you could use:

regEx = /^([A-Z][a-zA-Z]{0,19})?$/

If you want min lenght to be 1, means that you match single upper character you could use:

regEx = /^[A-Z][a-zA-Z]{0,19}$/