0

I have this function

function validateUsername(str,minL,maxL){// i'm passing validateUsername("asdf_1",2,8)
var exp=new RegExp(/^[a-z0-9_-]\w{"+minL+","+maxL+"}$/);
switch(exp.test(str)){
    case true: return true;
    case false: return false;
  }
}

I want to insert minimum Length and maximum length dynamically, But if above code used,its giving me false whether it should accept the string as true.

can anyone tell me, what should i use rather "+variable+" to insert the value dynamically.

Thanks in advance.

  • @k102- dude, i asked, what should i use so that i will get my answer true, in return case. this function is using for password validation. i know its little same question, but my problem is different. –  Jan 21 '14 at 10:07

2 Answers2

1

You can use the regex object constructor to build your regex from a string as stated here.

Example taken from linked answer :

var re = new RegExp("a|b", "i");
// same as
var re = /a|b/i;

In your case that would do something like :

function validateUsername(str,minL,maxL){// i'm passing validateUsername("asdf_1",2,8)
  var exp=new RegExp("^[a-z0-9_-]\w{" + minL + "," + maxL + "}$");
  /*
  why ???
  switch(exp.test(str)){
    case true: return true;
    case false: return false;
  }
  */
  return exp.test(str);
}
Community
  • 1
  • 1
Florian F.
  • 4,700
  • 26
  • 50
0

You can separate length validation from the pattern, something like this

if(str.length<minL || str.length>maxL){
// invalid length
}else{
var exp=new RegExp(/^[a-z0-9_-]\w$/);
 return exp.test(str)
}
Anil Maharjan
  • 441
  • 4
  • 14
  • This will cause result false, {required,required} in my case, otherwise false output. –  Jan 21 '14 at 10:04
  • i am not checking length, i want to insert dynamic minimum and maximum length inside my regEx. –  Jan 21 '14 at 10:15