lakenen
lakenen

Reputation: 3496

Why do some valid regular expressions not work with the html5 pattern attribute?

See this fiddle: http://jsfiddle.net/5vTc7/

If you open the console, you can see that the regular expression in the pattern attribute ((?=^[0-9]*(\.[0-9]+)?$)(?=.*[1-9])) works as expected from JS, but when you enter anything in the input and try to submit, it fails.

In case there's something wrong with my regular expression, I'm simply trying to limit it to numbers greater than 0. I'd like to use the number input (i.e., <input type="number"/>), but I can't, because it doesn't allow you to format the values (e.g., it will display 0.00000001 as 1e-8, which is undesirable).

I am clueless here. Is there something I'm missing? Why doesn't this work?

Upvotes: 2

Views: 1017

Answers (2)

Olaf Dietsche
Olaf Dietsche

Reputation: 74028

When you use the pattern with anchors, as specified in The pattern attribute, it will fail with Javascript as well

var pattern = '^(?=^[0-9]*(\.[0-9]+)?$)(?=.*[1-9])$';
var reg = new RegExp(pattern);
console.log(reg.test('1.0')); // will fail
console.log(reg.test('0.0')); // will fail

See modified JSFiddle

If you want to limit the input to non-null numbers, you can use

\d*[1-9]\d*(?:\.\d*)?|\d+\.\d*[1-9]\d*

This pattern requires at least one non-null digit either before or after the decimal point.

See JSFiddle

Upvotes: 3

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89557

You can try this pattern:

^(?:0+\.0*[1-9][0-9]*|0*[1-9][0-9]*(?:\.[0-9]+)?)$

Upvotes: -1

Related Questions