You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C#中验证邮箱?AngularJS邮箱验证代码报错求助

AngularJS Email Validation Fix & C# Implementation Guide

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:

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 04:12:16