前言
最近做了一个小需求,新建用户时输入的密码必须包含数字、小写字母、大写字符以及特殊字符,目的是为了增强密码的强度,如果没有其中一项,就需要弹出窗口进行提示。
正则表达式
对于此类字符串匹配的问题,用正则表达式(Regular Expression)来校验最好不过了。
正则表达式的使用方法有很多,如C Regex、C++ Regex以及boost::regex等等,本文使用VC++测试,主要使用ATL中两个模板类CAtlRegExp和CAtlREMatchContext。
下载ATL Server Library and Tools
VS2008中由于将ALT项目的部分代码剥离出去成为了独立的开源项目,需要用到ALT中正则表达式等功能就需要手动下载。
下载:http://atlserver.codeplex.com/
下载后解压到指定位置,将include目录加入VS工程的包含目录中去。
密码校验
1、 使用VS2008,新建基于对话框的MFC应用程序PassWordRegex;
2、 新建编辑框(IDC_EDIT_PASSWORD),设置属性password为True;
3、 为密码编辑框关联变量CString m_strPassWord;
4、 添加【OK】按钮响应如下:
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
void CPassWordRegexDlg::OnBnClickedOk()
{ UpdateData(); m_strPassWord.TrimLeft(); m_strPassWord.TrimRight(); //密码为空校验 if (m_strPassWord.IsEmpty()) { AfxMessageBox(_T("密码为空!")); return; } //密码正则表达式校验 if(!ChkPassWordEX()) { return; } OnOK(); } |
5、 添加密码正则表达式校验过程
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
BOOL CPassWordRegexDlg::ChkPassWordEX()
{ CAtlRegExp<> reExp; CAtlREMatchContext<> mcMatch; REParseError status = REPARSE_ERROR_OK; //数字 status = reExp.Parse(_T(".*[0-9].*")); if (REPARSE_ERROR_OK != status) { return FALSE; } if (!reExp.Match(m_strPassWord, &mcMatch)) { AfxMessageBox(_T("密码中必须包含数字!")); return FALSE; } //小写字母 status = reExp.Parse(_T(".*[a-z].*")); if (REPARSE_ERROR_OK != status) { return FALSE; } if (!reExp.Match(m_strPassWord, &mcMatch)) { AfxMessageBox(_T("密码中必须包含小写字母!")); return FALSE; } //大写字母 status = reExp.Parse(_T(".*[A-Z].*")); if (REPARSE_ERROR_OK != status) { return FALSE; } if (!reExp.Match(m_strPassWord, &mcMatch)) { AfxMessageBox(_T("密码中必须包含大写字母!")); return FALSE; } //特殊字符 status = reExp.Parse(_T(".*[~!@#$%^&*].*")); if (REPARSE_ERROR_OK != status) { return FALSE; } if (!reExp.Match(m_strPassWord, &mcMatch)) return TRUE; |
注意:在PassWordRegexDlg.cpp中加入头文件:#include <atlrx.h>
6、编译运行