ShriCoder ShriCoder - 5 months ago 7
Javascript Question

Need a regex for float values

I have a number field in the form and am validating that number field for float values. But I need to restrict the float number to only one period (

.
)

For example:
122.00


But now its taking input like this also:
123.00.
.
I dont want allow another period (
.
) in the end again.

Is there any regex for this?

Answer

Something like this might work for you:

/^\d+(?:\.\d+)?$/

It matches \digets maybe followed by literal period (.) and more digits:

var regex = /^\d+(?:\.\d+)?$/;
console.log(regex.test('1234')); // true
console.log(regex.test('12.34')); // true
console.log(regex.test('12.')); // false
console.log(regex.test('12.3.4')); // false