1

I want to control form of user input in textarea on my page. The input has to look exactly like this:

enter image description here

That means only three values in one row and semicolon between the first and the second and between the second and the third value.

By now I am using this regex to validate it:

^((([^;]+);([^;]*);([^;]+))\n?)*$

It does not work 100%, because it validates input like

value1;value2;value3
value1

as valid. Problem is the new line and the beginning of next value1. It seems like until first semicolon written after the value1, the value1 is still appended to the end of the value3 in previous line. How should I change the regex to disable this and mark every new incomplete line as invalid?

I created an JS fiddle to demonstrate: https://jsfiddle.net/tw2y5omc/3/

witcher
  • 135
  • 2
  • 13

1 Answers1

1

Following regex:

^((?:[^;]+;){2}(?:[^;\n\r]+))$
# captures everything into a group
# matches everything except a semicolon, followed by a semicolon two times
# afterwards everything except a semicolon or newlines being bound to the end of the string

If you want to also allow empty values, use a star instead:

^((?:[^;]*;){2}(?:[^;\n\r]*))$

Demo on regex101.com

Jan
  • 42,290
  • 8
  • 54
  • 79
  • Still the same process. This kind of input should not be valid: https://regex101.com/r/xS6iC0/4 – witcher Jan 27 '16 at 12:30
  • Thank you. I only changed the {2} to (?:[^;]*;) because middle value is optional. – witcher Jan 27 '16 at 13:05
  • Sorry, but it didnt helped yet. For example either this input should not be valid but it is: https://regex101.com/r/xS6iC0/6. Regex does not have back check for previous lines. – witcher Jan 27 '16 at 13:47
  • @witcher: Excluded the new line characters in all three groups - https://regex101.com/r/xS6iC0/7 Optional parts weren't obvious in your original question. – Jan Jan 27 '16 at 14:04
  • It was part of the original regex (you can see the * char between semicolons: ...;([^;]*);... where the value2 supposed to be). But I understand you needn't notice. I tried to add \n\r to every value part just before your last comment, but it is not the answer, because now only one row in textarea is marked as valid. Take a look: https://jsfiddle.net/tw2y5omc/8/. When you try it with with only one row, its ok but not with multiple. – witcher Jan 27 '16 at 14:22