邮箱格式验证

转载自 http://blog.csdn.net/waylife/article/details/9623783

2. 编写一个程序,要求用户输入邮件地址,Email地址必须符合规范。编写一个邮件地址格式不符合规范的自定义异常继承自ApplicationException,如果邮件地址格式不符合规范,则抛出这个异常。

    提示:邮件地址规范是:确保电子邮件地址含有符号“@”,且只出现一次;含有符号“.”,且只出现一次;符号“_”不能出现在电子邮件地址的开头。

//1.EmailCheckException.cs

//By wangyun 2011,11,26 at Dormitory 3#15**

//CopyRight WorldsList Soft

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Windows.Forms;

using System.Text.RegularExpressions;

 

namespace S6_2

{

    public partial class EMailCheck : Form

    {

        bool EmailCheckResult=false;

        string EmailPattern = @"^([A-Za-z0-9]{1}[A-Za-z0-9_]*)@([A-Za-z0-9_]+)[.]([A-Za-z0-9_]*)$";//E-Mail地址格式的正则表达式

        //邮件地址规范是:除@和.外只能输入字母,数字和下划线,@和.只出现一次,符号"_"不能出现在电子邮件地址的开头.不同的邮件服务器提供商的规则有所不同

        public EMailCheck()

        {

            InitializeComponent();

        }

 

        private void buttonCheck_Click(object sender, EventArgs e)

        {

            ////先去除用户输入的前导空格和尾部空格再判断

            textBoxMail.Text = textBoxMail.Text.Trim();

            EmailCheckResult=Regex.IsMatch(textBoxMail.Text, EmailPattern);

            try

            {

                if (!EmailCheckResult)

                {

                    textBoxResult.Text = textBoxMail.Text+"不是一个E-Mail地址";

                    throw new EmailCheckException("不是有效的EMail地址");

                }

                else

                {

                    textBoxResult.Text = textBoxMail.Text + "是一个E-Mail地址";

                }

            }

            catch (EmailCheckException ex)

            {

                ex.ShowNotEmailAddressError();

            }

        }

    }

}

//2.EmailCheckException.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
 
namespace S6_2
{
    class EmailCheckException:ApplicationException
    {
        string message;
        public EmailCheckException(string message) : base(message)
        {
            this.message = message;
        }
        public void ShowNotEmailAddressError()
        {
            MessageBox.Show(message, "出错提示!", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }
}
3.程序运行图
 [C]电子邮件格式验证 - WorldsList - 走在云海之巅
posted @ 2017-03-20 13:52  弄丢的小可爱🌸  阅读(457)  评论(0)    收藏  举报