偶然间,给小H同志的邮件地址验证正则表达式,居然不能让他在Regex.IsMatch中正确应用,我当时觉得很奇怪,这个正则表达式用了好几年了,从来没有在验证控件中出过错,怎么到了Regex.IsMatch就完全不行了呢?先给出正则表达式,

\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*

在Regulator中测试一下,的确是只能匹配字符串中的邮件地址,但不是保证整个字符串为合法的邮件地址。看来验证控件做的工作不仅仅是IsMatch了。赶紧看看代码,验证一下我的猜测。

protected override bool EvaluateIsValid()
{
    string controlValidationValue = base.GetControlValidationValue(base.ControlToValidate);
    if ((controlValidationValue == null) || (controlValidationValue.Trim().Length == 0))
    {
        return true;
    }
    try
    {
        Match match = Regex.Match(controlValidationValue, this.ValidationExpression);
        return ((match.Success && (match.Index == 0)) && (match.Length == controlValidationValue.Length));
    }
    catch
    {
        return true;
    }
}

看来还是功力不够啊~

如果要在代码中验证邮件地址的有效性,可以采用上述微软的方式,也可以使用另外的正则表达式,对字符串的开始和结束进行更多的约束。推荐如下的正则表达式:

1)来自于微软MSDN帮助中的邮件验证举例

^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$

2)来自于http://www.dreamincode.net/code/snippet1374.htm的邮件验证代码

^[-a-zA-Z0-9][-.a-zA-Z0-9]*@[-.a-zA-Z0-9]+(\.[-.a-zA-Z0-9]+)*\. (com|edu|info|gov|int|mil|net|org|biz|name|museum|coop|aero|pro|tv|[a-zA-Z]{2})$