Asad
Asad

Reputation: 3160

regular expression to check only one decimal point

I have following regular expression to check only one decimal point for type number tag in html

^-?[0-9]*\\.?[0-9]*$

but this regular failed to check If I put decimal at the end e.g 12.12. what further I have to add to check this

Upvotes: 0

Views: 2068

Answers (3)

wp78de
wp78de

Reputation: 18950

I think your regex can be easily fixed using a + instead of last * quantifier:

^-?[0-9]*\.?[0-9]+$

Tests:

const regex = /^-?[0-9]*\.?[0-9]+$/gm;
console.log('regex.test?')
console.log('12 = ' + regex.test('12'));
console.log('12. = ' + regex.test('12.'));
console.log('12.1 = ' + regex.test('12.1'));
console.log('12.12. = ' + regex.test('12.12.'));
console.log('-1 = ' + regex.test('-1'));
console.log('-1. = ' + regex.test('-1.'));
console.log('-1.2 = ' + regex.test('-1.2'));
console.log('-.12 = ' + regex.test('-.12'));
console.log('-. = ' + regex.test('-.'));
console.log('-. = ' + regex.test('-'));
console.log('. = ' + regex.test('.'));

Demo

Upvotes: 2

landru27
landru27

Reputation: 1702

The simplest way to allow a possible . at the end is to have \.? just before the $. Also, the double \ looks wrong (unless you need it for escaping a \ in the context in which you are using it):

^-?[0-9]*\.?[0-9]*\.?$

But please recognize that your regex does not require any actual digits, so will match some non-numbers, like ., -. and (with my edit) -.. The above regex will also match an empty string!

You will want to either change your regex to require digits, or take into account somewhere else that they might not be there.

Upvotes: 0

Hany Habib
Hany Habib

Reputation: 1405

Can you try the below : [1-9]\d*(\.\d+)?$

Upvotes: 0

Related Questions