Strange validator behaviour in AngularJS 1.5.11

22 views Asked by At

Our application is still using AngularJS 1.5.11 but I've tested the included example also with version 1.7.2 and get the same results.

The problem is the strange behavior of the validateNumber function. The validation seems to be flipping between true and false for each character typed. The validateMin and validateMax functions are working as expected.

The example code can be found here: https://codepen.io/kdbruin/pen/MBmXYz

Any insights as to why this is happening?

2

There are 2 answers

0
Kees de Bruin On BEST ANSWER

It seems that the regular expression is at fault here. When using

var numberRegexp = new RegExp("^[-+]?\\d+(" + (decimalSeparator === "." ? "\\." : decimalSeparator) + "\\d*)?$", "i");

the problem disappears. So it seems that the original "g" flag should not be used.

1
jsruok On

Maybe this is the culprit?

test() called multiple times on the same global regular expression instance will advance past the previous match.

MDN

Easiest fix might be to change

var result = numberRegexp.test(modelValue);

to

var result = numberRegexp.search(modelValue) !== -1;