我正在构建一个应用程序,该应用程序将首先部署到特定的大学校园。
我想确保当用户注册并提供他们的电子邮件地址时,这是他们学校提供的电子邮件,以确保只有合法的学生才能使用该服务。
是否有人有任何示例或想法来实现这一目标?也许有一个自定义的验证属性?
注意:
更具体地说,我只需要确保他们输入的电子邮件是.edu电子邮件地址即可
看起来正则表达式是必经之路...任何人都可以提供有关正确表达的指导吗?
请您参考如下方法:
我将创建一个正则表达式属性和自定义DataAnnotation。在全局中的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 person@someplace.com, some.person@someplace.com, some_person@some+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; }
}
}