我正在構建一個應用程序,最初將推出到特定的大學校園。如何驗證電子郵件來自ASP.NET MVC中的特定域?
我想確保,當用戶註冊,並提供他們的電子郵件地址,這是他們學校提供的電子郵件,確保只有合法的學生都可以使用該服務。
有沒有人對如何做到這一點的任何實例或想法?也許有一個自定義驗證屬性?
注: 更具體地說,我只需要確保他們進入電子郵件是.edu的電子郵件地址
看起來像正則表達式是要走的路...誰能提供了一些指導正確的表達?
我正在構建一個應用程序,最初將推出到特定的大學校園。如何驗證電子郵件來自ASP.NET MVC中的特定域?
我想確保,當用戶註冊,並提供他們的電子郵件地址,這是他們學校提供的電子郵件,確保只有合法的學生都可以使用該服務。
有沒有人對如何做到這一點的任何實例或想法?也許有一個自定義驗證屬性?
注: 更具體地說,我只需要確保他們進入電子郵件是.edu的電子郵件地址
看起來像正則表達式是要走的路...誰能提供了一些指導正確的表達?
我將創建一個正則表達式屬性和自定義DataAnnotation。在Global_中的Application_Start下注冊註釋。然後,您可以將驗證用作模型客戶端和服務器端的DataAnnotation。我有一個RegularExpressAttributes.cs類,它包含我所有常用的正則表達式;我所做的就是把它放到我的項目中。如果人們希望它只是讓我知道。
的觀點:
<div class="editor-field span-7">
@Html.LabelFor(model => model.EmailAddress)
@Html.EditorFor(model => model.EmailAddress)
@Html.ValidationMessageFor(model => model.EmailAddress)
</div>
正則表達式屬性
using System;
using System.Collections.Generic;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
namespace ProjectsMVC.Helpers
{
#region RegularExpressionAttributes
/// <summary>
/// Email validation regular expression attribute
/// </summary>
/// <remarks>Validates [email protected], [email protected], [email protected]+place.com and combinations thereof.</remarks>
public class ValidateEmailAttribute : RegularExpressionAttribute
{
// public ValidateEmailAttribute()
// : base(@"^\S?([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$") { }
public ValidateEmailAttribute()
: base(@)@"^\S?([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@someplace.com$") {}
}
#region DataAnnotationsModelValidator
public class EmailValidator : DataAnnotationsModelValidator<ValidateEmailAttribute>
{
#region Properties
/// <summary>
/// Error message
/// </summary>
private readonly string _errorMessage;
/// <summary>
/// Regular expression pattern
/// </summary>
private readonly string _pattern;
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="EmailValidator"/> class.
/// </summary>
/// <param name="metaData">The meta data.</param>
/// <param name="context">The context.</param>
/// <param name="attribute">The attribute.</param>
public EmailValidator(ModelMetadata metaData, ControllerContext context, ValidateEmailAttribute attribute)
: base(metaData, context, attribute)
{
this._errorMessage = attribute.ErrorMessage;
this._pattern = attribute.Pattern;
}
#endregion
#region Methods
/// <summary>
/// Retrieves a collection of client validation rules.
/// </summary>
/// <returns>A collection of client validation rules.</returns>
public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()
{
var rule = new ModelClientValidationRegexRule(this._errorMessage, this._pattern);
return new[] { rule };
}
#endregion
}
}
Global.ascx.cs
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
// Register custom model validators
DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(ValidateEmailAttribute), typeof(EmailValidator));
}
最後的型號,User.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using ProjectsMVC.Helpers;
namespace ProjectsMVC.Models
{
[MetadataType(typeof(User_Validation))]
public partial class User
{
public string ProperName
{
get
{
return string.Format("{0} {1}", this.FirstName, this.LastName);
}
}
public string DirectoryName
{
get
{
return string.Format("{0}, {1}", this.LastName, this.FirstName);
}
}
public string IsUserActive
{
get
{
return Dictionaries.TrueOrFalse.First(t => t.Key == this.IsActive).Value.ToString();
}
}
}
public class User_Validation
{
[Display(Name = "eName")]
[Required(ErrorMessage = "required")]
[ValidateEname(ErrorMessage = "invalid")]
public string UserName { get; set; }
[Display(Name = "First DirectoryName")]
[Required(ErrorMessage = "required")]
public string FirstName { get; set; }
[Display(Name = "Last DirectoryName")]
[Required(ErrorMessage = "required")]
public string LastName { get; set; }
[Display(Name = "Email Address")]
[Required(ErrorMessage = "required")]
[ValidateEmail(ErrorMessage = "invalid")]
public string EmailAddress { get; set; }
[Display(Name = "Active User")]
[Required(ErrorMessage = "required")]
public bool IsActive { get; set; }
}
}
自定義驗證屬性是你說的嗎?這裏有一個指南:http://msdn.microsoft.com/en-us/gg618485
如果用戶屬於特定的大學需要有特定的電子郵件後綴。 您可以將其存儲在表格中,然後在用戶登錄系統時根據學院檢查後綴 。
如果您需要檢查有效的電子郵件地址,你可以使用正則表達式。
請參閱示例代碼C#來檢查有效的電子郵件。
Regex re = new Regex(@"\w.\[email protected]{1,1}\w[.\w]?.\w");
return re.IsMatch(email);
我如何修改這個來驗證電子郵件結束int「.edu」? – stephen776 2012-01-16 16:41:52
這個工作:正則表達式(@「\ w。\ w @ {1,1} \ w [。\ w] ?. edu」); ?? – stephen776 2012-01-16 16:42:23
它爲我工作 – 2012-01-16 20:03:22
有RemoteAttribute
驗證屬性(RemoteAttribute Class)。 在其參數中,您可以指定可以執行驗證過程的控制器的操作。
如果您正在尋找自定義驗證器請參考this article,它對MVC模型驗證有很好的解釋。
您應該使用正則表達式屬性作爲模型中電子郵件字段的驗證程序。這在文章中也有解釋。
使用RegularExpressionAttribute,構建適當的正則表達式您的特定領域。
理想的情況下,我們能有一所學校降了下來,學生需要選擇學校,並輸入電子郵件地址。
然後我們可以有一個學校名稱和電子郵件格式的映射。
school name - ABC
email format - [\w]+[\.\-\_]?[\w][email protected][edu|org]
根據供應商的不同,電子郵件格式可能不同。
這些東西可以是web.config中
<Web.config>
<appsettings>
<add key="ABC" value="[\w]+[\.\-\_]?[\w][email protected][edu|org]"/>
.
.
.
我們可以讀取使用ConfigurationManager中的配置價值的一部分。
而且,你的模型可以從IValidatableObject繼承並重寫Validate方法來驗證電子郵件地址,如果沒有有效的拋回ValidationRessult,它可以顯示在查看驗證錯誤
你想驗證實際域名是否存在,或者只是以.edu結尾?以.edu結尾的 – epignosisx 2012-01-16 16:09:00
很可能就足夠了。另一種選擇,我想是將域存儲在我的數據庫中,並檢查它。 – stephen776 2012-01-16 16:12:02
有沒有一種使用正則表達式檢查.edu的快速方法? – stephen776 2012-01-16 16:12:58