如何在C#中验证邮箱?AngularJS邮箱验证代码报错求助
Fixing Your AngularJS Email Validation Issue
Let's tackle your AngularJS problem first. The most probable cause of your error is that your input isn't wrapped in a <form> element with the name="myForm" attribute—you’re referencing myForm.Email.$error in your ng-show directives, so the form needs this explicit name to be accessible in the scope.
Another tweak: your current regex only matches lowercase emails. Adding the /i modifier makes it case-insensitive, which is more user-friendly since email addresses aren’t case-sensitive by standard.
Here’s the corrected code:
<form name="myForm" novalidate> <input type="text" ng-model="Email" id="txtEmail" ng-pattern="/^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$/i" name="Email" placeholder="Email" required > <span ng-show="myForm.Email.$dirty && myForm.Email.$error.pattern">Please enter valid Email!</span> <span ng-show="myForm.Email.$dirty && myForm.Email.$error.required">*</span> </form>
I added novalidate to disable browser default validation (so Angular’s validation takes full control) and $dirty to only show errors after the user interacts with the field—this avoids annoying immediate error popups when the page loads.
Implementing Email Validation in C#
For C#, you have two reliable approaches to validate email addresses:
1. Using the MailAddress Class (Recommended)
The .NET MailAddress class is purpose-built to handle email validation and covers all edge cases that regex often misses. It throws a FormatException if the email is invalid:
using System.Net.Mail; public bool IsValidEmail(string email) { try { var mailAddress = new MailAddress(email); return true; } catch (FormatException) { return false; } }
2. Using a Regular Expression
If you prefer regex, use a well-tested pattern that covers most valid email formats:
using System.Text.RegularExpressions; public bool IsValidEmailRegex(string email) { string pattern = @"^[^@\s]+@[^@\s]+\.[^@\s]+$"; return Regex.IsMatch(email, pattern, RegexOptions.IgnoreCase); }
Note: No regex can perfectly validate every possible email address (per RFC standards), so the MailAddress method is always the safer, more accurate choice.
内容的提问来源于stack exchange,提问作者JohnMathew

