Skip to main content

asp.net用正则表达式对密码进行格式验证

在asp.net中常用RegularExpressionValidator来对密码的格式进行第一次验证。现有密码格式要求如下:

  • 长度8-12位。
  • 至少有一个字母。
  • 至少有一个数字。
  • 至少有一个特殊字符(非数字和字母的字符,例如:!@#$%等)。

在MSDN里找asp.net membership密码强度验证相关的东西,里面有对6位以上,至少一数字和特殊字符的正则表达式如下"(?=.{6,})(?=(.*\d){1,})(?=(.*\W){1,})"。当我把短代码复制到RegularExpressionValidator里面才发现,即使是符合的规定的密码也不能通过验证。

查看asp.net的js文件,找到调用RegularExpressionValidator的函数:function RegularExpressionValidatorEvaluateIsValid(val) {
  var value = ValidatorGetValue(val.controltovalidate);
  if (ValidatorTrim(value).length == 0) {
    return true;
  }
  var rx = new RegExp(val.validationexpression);
  var matches = rx.exec(value);
  return matches != null && value == matches[0];
}

(?=pattern)就是所谓的“正向预查”,是个“非获取匹配”,也就是说如果不能匹配(?=pattern)的话,matches的值是null,即使匹配了,matches[0](最后一次匹配的值)的值也是空("")。

根据以上,修改RegularExpressionValidator中的ValidationExpression为"(?=.{8,12})(?=.*[0-9]+)(?=.*[a-zA-Z]+)(?=.*\W+)(.*)"

Comments

Popular posts from this blog

Python中的self

习惯上,任何Python类方法的第一个参数(对当前实例d的引用)都叫做self。这个参数扮演着C++或Java中的保留字this的角色,但self在Python中并不是一个保留字,它只是一个命名习惯。虽然如此,也请除了self之外不要使用其它的名字,这是一个非常坚固的习惯。 出自:《Dive Into Python》

Google Notebook整合了Google 书签

FF上一直装有Google笔记本的插件,一直没有到一面上去看,今天无意点到。发现多了个叫“Unfiled”的记事本,记得自己并未建过这么个东西,进去一看才发现,其实就是我的Google书签: 并且右下角也多了“Labels”,且与我Google书签中的相同。 其实人家的右上角的“ New features! ”里说得很清楚: Integration with Google Bookmarks Notebook is now integrated with Google Bookmarks. Your bookmarks will show up as a special Unfiled notebook, making Google Notebook a single place to collect and organize interesting web pages. To publish and collaborate, just drag and drop bookmarks into notebooks.