YYY
YYY

Reputation: 55

Regular Expression for XXXXXX.XX formatted number

I need to write a regular expression with this format: XXXXXX.XX There can be less than 6 digits, and the .XX part should be optional.

function checkFormat(el) {
    var ex = new RegExp(/ ^[0-9]{1,6}([.][0-9]{1,2})$/);
    var valid = ex.test(el.value);
    return valid;
}

What should be the right regular expression?

Upvotes: 1

Views: 4217

Answers (2)

Pedro Lobito
Pedro Lobito

Reputation: 99061

Make the . and last 2 digits optional (?:\.[\d]{2})?, i.e.:

/^\d{1,6}(?:\.\d{2})?$/

function checkFormat(el) {
    var ex = new RegExp(/^\d{1,6}(?:\.\d{1,2})?$/);
    var valid = ex.test(el);
    return valid;
}

document.write("12345 " + checkFormat(12345)+"<br>");
document.write("12345.002 " + checkFormat(12345.002)+"<br>");
document.write("12345.00 " +  checkFormat(12345.00)+"<br>");
document.write("123455555 " + checkFormat(123455555)+"<br>");

Regex101 Demo

Upvotes: 2

Arnaud Gueras
Arnaud Gueras

Reputation: 2062

Just add "?" to make the "( )" part optional, and I replace the [.] by \. and [0-9] by \d

/^\d{1,6}(\.\d{1,2})?$/

Upvotes: 3

Related Questions