Thursday, August 25, 2011

Escape your regular expressions in JavaScript

Always escape your regular expressions in JavaScript! Today I’ve literally spent 2 hours trying to understand why this wasn’t working:

var isPasswordValid = function(password){
  var regExp = new RegExp('^.*(?=.{6,})(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).*$');
  return regExp.test(password);
}

Eventually we found out that the reason was in NOT escaping the regular expression. The following piece of code works fine:

var isPasswordValid = function(password){
  var regExp = new RegExp('^.*(?=.{6,})(?=.*\\d)(?=.*[a-z])(?=.*[A-Z]).*$');
  return regExp.test(password);
} 

Pay attention to (?=.*\d) part of the expression.

2 comments:

m_silent said...

Зумарду хъамул даннов, Башир! :)

Bashir Magomedov said...

БарчаАЛЛгь! Вилассагу кьамул даннав, Мухаммад! :)