我知道这对游戏来说有点晚了,但这确实增加了验证,我发现它非常有帮助。有时,引用其他 jquery 版本的冲突 javascript/jQuery 插件/API 引用(例如:searchMeme.js)可能会导致问题,因此我为帐户登录操作创建了唯一的捆绑包。这些是我将采取的步骤:
1.为AccountController.cs创建一个单独的布局~/Views/Shared/_AccountLayout.cshtml。
2.使用以下命令创建新的~/Account/_ViewStart.csthml:
@{
Layout = "~/Views/Shared/_AccountLayout.cshtml";
}
3.在BundleConfig.cs中为AccountController创建两个css & js的bundle :
bundles.Add(new StyleBundle("~/Content/accountcss").Include(
"~/Content/site.css",
"~/Content/bootstrap.css",
"~/Content/font-awesome.css")); /*if using font-awesome */
bundles.Add(new ScriptBundle("~/bundles/accountjs").Include(
"~/Scripts/jquery-1.10.2.js",
"~/Scripts/jquery.validate.js",
"~/Scripts/jquery.validate.unobtrusive.js",
"~/Scripts/bootstrap.js"));//must be after jquery validate
4.在_AccountLayout.cshtml中引用head & body两端的bundle,如下:
<title>@ViewBag.Title</title>
<link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<meta name="viewport" content="width=device-width" />
@Styles.Render("~/Content/accountcss")
@Scripts.Render("~/bundles/modernizr")
@this.RenderSection("MetaContent", false)
@this.RenderSection("Styles", false)
</head>
@Scripts.Render("~/bundles/accountjs")
@this.RenderSection("Scripts", false)
</body>
*注意:确保引导程序在捆绑包中的 jqueryval 之后
5.确保您在~/Account/Login.cshtml、~/Account/Register.cshtml等中分别拥有@Html.ValidationMessageFor
每个输入字段。
<div class="form-group">
@Html.LabelFor(m => m.UserName, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.TextBoxFor(m => m.UserName, new { @class = "form-control" })
@Html.ValidationMessageFor(m => m.UserName, "", new { @class = "text-danger" })
</div>
</div>
6.使用 DataAnnotations 创建额外的自定义验证错误[RegularExpression(@"^([\w]{2,20})@?([\w]{2,20}).?[a-zA-Z]{2,3}$", ErrorMessage="")]
:
[Required(ErrorMessage = "*Username is required."), RegularExpression(@"^[\w+]{3,10}\s?([\w+]{3,15})$", ErrorMessage = "*Username can only be Alphanumeric"),StringLength(25, ErrorMessage = "The {0} must be at least {2} characters long and no bigger than {1} characters.", MinimumLength = 5)]
public string UserName { get; set; }
7.(可选)最后,如果您更改了密码的 DataAnotation,那么您还必须更改~/App_Start/IdentityConfig.cs中的密码策略,如下所示:
manager.PasswordValidator = new PasswordValidator
{
RequiredLength = 6,
RequireNonLetterOrDigit = false,
RequireDigit = true,
RequireLowercase = true,
RequireUppercase = true,
};
8.(可选)另外,请查看有关角色等的这篇文章。