Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to validate entire multiline text in angularjs

I need some help.
I have to construct a regex for angularjs ng-pattern attribute. The regex has to validate a text, not each line or some pieces. The text has to contains some amounts with exactly 2 decimals and each amount should be entered in the new line. Also, spaces are accepted before and after each amount. If one line contains 2 amount then the entire text is not valid.

For example this text is valid because each amount is entered in the new line:

123.34 
12345.56
2.54

This example is not valid because one line contains 2 amounts:

12.43
123.32 2345.54
124.43

This example is not valid because one amount does not contains 2 decimal(each amounts has to be with exactly 2 decimals):

123
123.43
123.65

My best try is ^(([0-9]+[.][0-9]{2})\s*)+$ and it can be tested here. But my regex it's not enough because it accept text with multiple amounts in the same line.

Thanks

like image 579
Gryph G Avatar asked Feb 02 '18 09:02

Gryph G


1 Answers

Regex is not my strong point, so there may be a much simpler way to do this, but this does meet your requirements:

^(([^\S\r\n]*[0-9]+[.][0-9]{2}[^\S\r\n]*)\n)*(([^\S\r\n]*[0-9]+[.][0-9]{2}[^\S\r\n]*))$

Effectively what it does is ensure that the last line (without a newline character at the end) is always present, but also allows for optional lines before that which end with a newline (\n).

We also use the [^\S\r\n] part in place of \s to ensure that it checks for whitespace characters excluding newline, as the newline is what causes an issue with validating multiple values on the same line.

Here is a working example

like image 132
musefan Avatar answered Sep 29 '22 08:09

musefan