Altering a regex float expression to enforce a leading number before decimal point

Viewed 58

I have the following regex expression that validates via jquery a textbox element in html.

/^-?\d*[.]?\d*$/

I would like to alter this so that the decimal point can only be added if it has a leading number before it.

If someone could provide me the solution I'd be very grateful.

1 Answers

Just add + quantifier after first \d

^-?\d+[.]?\d*$

const n1 = '.1';
const n2 = '0.1';
const n3 = '-0.1';
const regex = /^-?\d+[.]?\d*$/;

console.log(`${n1}  ==> ${regex.test(n1)}`);
console.log(`${n2} ==> ${regex.test(n2)}`);
console.log(`${n3} ==> ${regex.test(n3)}`);

Edit:

Above pattern will match strings that have no digits after the decimal such as "1.". If you want to enforce digits after decimal if decimal is present, use following regex

^-?\d+(\.\d+)?$

const n1 = '1.';
const n2 = '1.1';
const regex = /^-?\d+(\.\d+)?$/;

console.log(`${n1}  ==> ${regex.test(n1)}`);
console.log(`${n2} ==> ${regex.test(n2)}`);

Related