3

I am trying to validate text area. Format should be us following:

Text description: ${VARIABLE_NAME} \n
Text description: ${VARIABLE_NAME} 

Rules:

  1. Text description can contain a-zA-Z0-9 spaces and "_"
  2. Text description need to be followed ":"
  3. ":" can be followed with no or one space
  4. after ": " string need to start with "${"
  5. "VARIABLE_NAME" can contain only A-Z and "_"
  6. "VARIABLE_NAME" and line need to finish with "}"

Text can have multiple lines, every line need to follow all 6 rules.

For now i have this regex const regex = new RegExp('[\\w+]:\\$\\{[A-Z]+}$', 'gs'); Just not sure how to handle multiple lines.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
user2994290
  • 329
  • 4
  • 13

2 Answers2

3

The requirements can be matched as follows:

  1. [\w ]+ 2. → : 3. →  ? 4. → \$\{ 5. → [A-Z_]+ 6. → }

Put into a (?: non capturing group (?:\n|$)) + for one or more lines.

^(?:[\w ]+: ?\$\{[A-Z_]+}(?:\n|$))+$

See this demo at regex101 or a JS demo at tio.run (use \r?\n for CRLF support)

bobble bubble
  • 16,888
  • 3
  • 27
  • 46
2

You can use

/^[\w ]+:[^\S\r\n]?\${[A-Z_]+}(?:\r?\n[\w ]+:[^\S\r\n]?\${[A-Z_]+})*$/

See the regex demo. Details:

  • ^ - start of string
  • [\w ]+ - one or more alphanumeric/underscore/space chars
  • : - a colon
  • [^\S\r\n]? - an optional horizontal whitespace
  • \${ - a ${ string
  • [A-Z_]+ - one or more uppercase ASCII letters or underscores
  • } - a } char
  • (?:\r?\n[\w ]+:[^\S\r\n]?\${[A-Z_]+})* - zero or more repetitions of the CRLF or LF line ending sequence followed with the above explained pattern
  • $ - end of string.
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563