使用正则表达式验证电子邮件地址 [英] Validating email address using Regular expression

查看:112
本文介绍了使用正则表达式验证电子邮件地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用正则表达式验证两个不同的域电子邮件地址。

我们有两个域名,例如mydomain.com和newdomain.com.au



对于单个域名,它的工作方式如下:



[RegularExpression(@^ [a-zA-Z0-9 ._%+ - ] +(@ mydomain\.com)$,ErrorMessage =注册仅限于mydomain)]



我如何添加两个域,任何人都可以协助吗?

解决方案

,ErrorMessage =注册仅限于mydomain)]



如何添加这两个域,任何人都可以提供帮助吗?


< blockquote>你不需要正则表达式。这个验证已经在类 System.Uri 中由它的构造函数完成。你可以在这里找到一个例子:https://msdn.microsoft.com/en-us/library/ system.uri.urischememailto%28v = vs.110%29.aspx [ ^ ]。



另外,你应该处理和捕获异常,因为字符串可能不是有效。有关可抛出的异常,请参阅: https:// msdn .microsoft.com / zh-CN / library / z6c2z492%28v = vs.110%29.aspx [ ^ ]。



如果你不这样做在测试字符串中需要mailto:,你必须在输入字符串前加上它。您可以从 System.Uri.UriSchemeMailto 中获取它。



将它们放在一起以创建验证。作为额外的奖励,你不仅会获得真/假答案,而且,如果验证成功, Systen.Uri 的实例,这是更有用/更有用的比原始字符串。



-SA


你的正则表达式应该像





RegularExpression(@^ [a-zA-Z0-9 ._%+ - ] +((@ mydomain\.com)|( @ newdomain\.com.\au))

I need to validate two different domain email addresses using Regular Expression.
we have two domains e.g mydomain.com and newdomain.com.au

For single domain it is working as:

[RegularExpression(@"^[a-zA-Z0-9._%+-]+(@mydomain\.com)$", ErrorMessage = "Registration limited to mydomain")]

How can I add both of the domains, can anyone assist?

解决方案

", ErrorMessage = "Registration limited to mydomain")]

How can I add both of the domains, can anyone assist?


You don't need regular expression. This validation is already done in the class System.Uri, by its constructor. You can find an example here: https://msdn.microsoft.com/en-us/library/system.uri.urischememailto%28v=vs.110%29.aspx[^].

Also, you should handle and catch exceptions, as the string might not be valid. For the exceptions which can be thrown, please see: https://msdn.microsoft.com/en-us/library/z6c2z492%28v=vs.110%29.aspx[^].

If you don't expect "mailto:" in the test string, you have to prefix your input string with it. You can take it from System.Uri.UriSchemeMailto.

Put it all together to create the validation. As an additional bonus, you will get not just true/false answer, but, in case of successful validation, the instance of Systen.Uri, which is much more useful/informative than raw string.

—SA


Your Regex should be like


RegularExpression(@"^[a-zA-Z0-9._%+-]+((@mydomain\.com)|(@newdomain\.com.\au))


这篇关于使用正则表达式验证电子邮件地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆