user7693832
user7693832

Reputation: 6859

How to limit the length using regex?

I want to use regex to verify the length(6-18)'s string:

var reg = new RegExp('^[a-zA-Z_0-9]{6, 18}$')

var res = reg.test('aaaaaa')

console.log(res)   // but there I get false

whether my regex is write wrong?

Upvotes: 0

Views: 60

Answers (2)

th3n3wguy
th3n3wguy

Reputation: 3747

Here is an alternative if you don't want to use Regular Expressions:

function isCorrectLength(str, min, max) {
  return str && typeof str === 'string' && str.length >= min && str.length <= max;
}

console.log(isCorrectLength('testing', 6, 18));
console.log(isCorrectLength('test', 6, 18));

Upvotes: 0

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522762

I think you have a rogue space in the bracketed quantity. Remove it and your code will work:

var reg = new RegExp('^[a-zA-Z_0-9]{6,18}$');  // NOT {6, 18}
var res = reg.test('aaaaaa');
console.log(res);

Upvotes: 2

Related Questions