C# 如何让文本框只接受有效的电子邮件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29820568/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I make a textbox only accept a valid email?
提问by Nickz2
I would like my textbox to check if the email that is entered into the textbox is valid.
我想让我的文本框检查输入到文本框中的电子邮件是否有效。
So far I have got:
到目前为止,我有:
if (!this.txtEmail.Text.Contains('@') || !this.txtEmail.Text.Contains('.'))
{
MessageBox.Show("Please Enter A Valid Email", "Invalid Email", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
But this only tests if it has a '@' and a '.' in it.
但这仅测试它是否具有“@”和“.”。在里面。
Is there a way to make it check to see if it has .com etc. and only one '@'?
有没有办法让它检查它是否有 .com 等,并且只有一个“@”?
采纳答案by Hyman
.NET can do it for you:
.NET 可以为您做到:
try
{
var eMailValidator = new System.Net.Mail.MailAddress("[email protected]");
}
catch (FormatException ex)
{
// wrong e-mail address
}
回答by Matheno
回答by IglooGreg
If you're developing a web app, modern browsers support HTML5, so you can use <input id="txtEmail" type="email" runat="server" />instead of a TextBox and it will validate the input is an email in the browser (but you should also validate it in your code). Use txtEmail.Value to get the text string.
如果您正在开发 Web 应用程序,现代浏览器支持 HTML5,因此您可以使用<input id="txtEmail" type="email" runat="server" />而不是 TextBox,它会在浏览器中验证输入是电子邮件(但您也应该在代码中验证它)。使用 txtEmail.Value 获取文本字符串。

