Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex for non-specific versioning in JavaScript

I'm trying to set up a way to prevent inputs into certain fields in JavaScript. Most of my fields check against /^\d*$/.test(value) which will prevent any input from being typed in or shown that's non-numeric.

One particular field uses /^[\d.]*$/.test(value) which allows any number of digits and a decimal to be placed in as well.

My issue is that the decimal regex allows any number, or combination specifically, of decimals to be input. I'm trying to prevent inputs like "....", "13.24..36", ".2.2", etc.

Could anyone provide a regex that has to start with a number, end with a number, can have decimal or no decimal, and prevents two decimals being put together? (like .. <- preventing the second unless another number follows)

like image 949
Derek Ball Avatar asked Aug 22 '26 21:08

Derek Ball


1 Answers

\d+(?:\.?\d+)? matches one or more digits and optionally a group of optionally a dot and some more digits

This still allows matches like .2 but you could check that the digits are not preceded by a dot: (?<!\.) and not followed by a dot: (?!\.)

The full pattern then becomes (?<!\.)\d+(?:\.?\d+)?(?!\.). Keep in mind that the negative lookbehind (?<!...) is not yet supported in every JavaScript environment. (Node.js and Chrome support it at present).

like image 192
Zwiers Avatar answered Aug 25 '26 11:08

Zwiers