0

I know this question has been asked a few times and the answers are unique to the specific regexes in question, but aside from that, I've tried to make sure that I'm escaping characters that have special meaning. Whilst this regex plays ball on https://regex101.com (in JavaScript mode), in my app it's having other ideas!

^([A-z0-9][A-z0-9 '\-,\.:\&]{0,245}[A-z0-9]|[A-z0-9][A-z0-9 '\-,\.:\&]{1,244}[A-z0-9])$

This is what I tell the user: 2-247 characters, start and end with A-z 0-9, permitted special characters: ' - , . : &

...but as you see, I'm actually also ensuring that the string starts with:

a) Two non-special characters, or

b) One non-special character followed by a special character, as long as that special character is followed by one or more non-special characters.

This is how I'm implementing the regex:

var nameRegex = new RegExp("^([A-z0-9][A-z0-9 '\-,\.:&]{0,245}[A-z0-9]|[A-z0-9][A-z0-9 '\-,\.:&]{1,244}[A-z0-9])$");

if (!nameRegex.test(formElements[i].value)) {
    // validation stuff here
}

Everything the regex intends on doing, it does. I've tested every condition that I'm checking for. But it does more. Regex 101 disallows a string like d*d, but my app? Perfectly fine.

I'll try .match instead of .test, maybe .test isn't the tool I think I need for this job?

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
Zuno
  • 433
  • 1
  • 7
  • 17
  • Why `new Regex()`? `var nameRegex = /^([A-z0-9][A-z0-9 '\-,\.:&]{0,245}[A-z0-9]|[A-z0-9][A-z0-9 '\-,\.:&]{1,244}[A-z0-9])$/;` – Andreas Apr 14 '20 at 12:21
  • So many issues, and all are so frequent. Please see the linked threads on top of your question. Note `[A-z]` does not only match ASCII letters, use `[A-Za-z]`. And certainly use backslashes properly in a string literal. Always use regex literals with static patterns (when not built from variables). – Wiktor Stribiżew Apr 14 '20 at 12:21
  • Zoiks, it's been a while since I did anything with regex and that was in C#, I knew these things, I'm tired. I apologise! – Zuno Apr 14 '20 at 17:35

0 Answers0