Email Address Validation for ASP.NET

前端 未结 8 856
梦如初夏
梦如初夏 2020-12-01 13:45

What do you use to validate an email address on a ASP.NET form. I want to make sure that it contains no XSS exploits.

This is ASP.NET 1.1

8条回答
  •  庸人自扰
    2020-12-01 14:18

    You should always do server side validaton as well.

    public bool IsValidEmailAddress(string email)
    {
        try
        {
            var emailChecked = new System.Net.Mail.MailAddress(email);
            return true;
        }
        catch
        {
            return false;
        }
    }
    

    UPDATE

    You can also use the EmailAddressAttribute in System.ComponentModel.DataAnnotations. Then there is no need for a try-catch to it's a cleaner solution.

    public bool IsValidEmailAddress(string email)
    {
        if (!string.IsNullOrEmpty(email) && new EmailAddressAttribute().IsValid(email))
            return true;
        else
            return false;
    }
    

    Note that the IsNullOrEmpty check is also needed otherwise a null value will return true.

提交回复
热议问题