2

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?

4
  • I'd suspect that the pattern attribute is implemented in-core of the browser (i.e: not in the JavaScript engine) and whatever regexp library they're using can't handle the zero-width assertion. Commented Dec 26, 2013 at 23:12
  • Aha! It needs to match the whole input value (not just some subset)... try using anchors? Commented Dec 26, 2013 at 23:15
  • 3
    Here is the relevant bit from the What Working Group documentation: whatwg.org/specs/web-apps/current-work/multipage/… Commented Dec 26, 2013 at 23:17
  • This implies that the regular expression language used for this attribute is the same as that used in JavaScript, except that the pattern attribute is matched against the entire value, not just any subset (somewhat as if it implied a ^(?: at the start of the pattern and a )$ at the end). whelp. I'm wrong (assuming the implementation works as the WG drafts describe it. Commented Dec 26, 2013 at 23:19

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

Very interesting. Thanks for the answer! Would there be anything wrong with just adding .* to the end of my original regex?
-1

You can try this pattern:

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

1 Comment

I didn't down vote, but I'm guessing it's because you didn't answer the question ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.