prasanth
prasanth

Reputation: 75

Regular Expression to check number length using javascript and allowing length between 6 and 8

I want to check the number length exists between 6 and 8, I tried in many ways but it is not working for me. Can any one help me with these?

My code:

Method 1:

regex = RegExp(/[-]{0,1}[\d{6,8}]*[\.]{0,1}[\d{6,8}]+/g),

Method 2:

regex = RegExp(/[-]{0,1}[\d]{6,8}*[\.]{0,1}[\d]{6,8}+/g),

I have tried above two ways but nothing helped me in achieve this. Please help me with the solution.

Upvotes: 2

Views: 2242

Answers (3)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521674

If you want to detect strings which have just 8 digits, anywhere, in them, then consider this approach:

var number = "314159.32";
if (/^-?[0-9]+(?:\.[0-9]+)?$/.test(number) &&
    /^[0-9]{6,8}$/.test(number.replace(/[.-]/g, ""))) {
        console.log("valid");
}
else {
    console.log("invalid");
}

The difficulty of using a single regex here is the optional decimal component, which may or may not appear. But, assuming the input is a number, and has no decimal component, then the regex pattern needed is easy.

Upvotes: 4

Synchro
Synchro

Reputation: 37760

Your description doesn’t match what your attempts are doing.

Generally You’re using character classes unnecessarily. Try this, which matches numbers between 6 and 8 digits long, optionally preceded by a -:

regex = RegExp(/-?\d{6,8}/g);

If there are other patterns you want to match, describe them, and add examples.

Upvotes: 4

TaPO4eg3D
TaPO4eg3D

Reputation: 73

Your question is not very clear, please provide some samples of valid strings. But not I can suggest you to use this regex:

^\d{6,8}$

Upvotes: -1

Related Questions