这是代码,我在布局中加载所有Jquery脚本,但是,当我键入不同于confirm-password的密码时。它在光标移出确认密码字段后没有验证,我不知道为什么?这是Renderbody中的一个视图
USBBook.Models.RegistrationViewModel
@{
ViewBag.Title = "Registration";
}
<script type="text/javascript">
$(document).ready(function () {
$("CredentialForm").validate ({
rules: {
password: { required: true,
minlength: 5 },
confirm-password: {
required: true,
minlength: 5,
equalTo: "#password" }
},
messages: {
password: {
required: "Please provide password",
minlength: "Password must be at least 5 characters long" },
confirm-password: {
required: "Please provide password",
minlength: "Password must be at least 5 characters long",
equalTo: "Please check password" }
}
});
});
</script>
<h2 style="text-align: center">
Registration</h2>
<h3 style="margin-left: 85px">
Account Information</h3>
<hr style="width: 70%; margin: 0px 0px 0px 85px" />
@using (Html.BeginForm("Create", "Credential", new { id = "CredentialForm" }))
{
@Html.ValidationSummary(true)
<fieldset>
@Html.HiddenFor(model => model.AccountID)
<div class="editor-label">
<span class="red">*</span>@Html.LabelFor(model => model.Email)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Email)
@Html.ValidationMessageFor(model => model.Email)
</div>
<div class="editor-label">
<span class="red">*</span>@Html.LabelFor(model => model.Password)
</div>
<div class="editor-field" id="password">
@Html.EditorFor(model => model.Password)
@Html.ValidationMessageFor(model => model.Password)
</div>
<div class="editor-label">
<span class="red">*</span>Confirm Password
</div>
<input id="confirm-password" class="editor-field" type="password" />
<p>
<input class="button" style="margin-left: 55px" type="submit" value="Submit" />
</p>
</fieldset>
这些是在布局中呈现的脚本:
<script src="../../Scripts/jquery-1.10.2.min.js" type="text/javascript"></script>
<script src="../../Scripts/jquery.validate.min.js" type="text/javascript"></script>
<script src="../../Scripts/jquery.validate.unobtrusive.min.js" type="text/javascript"></script>
我需要验证密码并确认密码字段,电子邮件由MVC验证。
感谢您的帮助
答案 0 :(得分:4)
您可以轻松简单地完成任务:
为密码和确认密码添加验证属性
[Required(ErrorMessage = "Password required")]
[StringLength(int.MaxValue, MinimumLength = 6, ErrorMessage = "Password is at least 6 characters.")]
public string Password { get; set; }
[CompareAttribute("Password", ErrorMessage = "Password doesn't match.")]
public string ConfirmPassowrd { get; set; }
在你的剃刀中,使用简单,无需添加jquery来处理确认密码
<div class="editor-label">
<span class="red">*</span>@Html.LabelFor(model => model.Password)
</div>
<div class="editor-field" id="password">
@Html.EditorFor(model => model.Password)
@Html.ValidationMessageFor(model => model.Password)
</div>
<div class="editor-label">
<span class="red">*</span>Confirm Password
</div>
<div class="editor-field" id="confirmPassword">
@Html.EditorFor(model => model.ConfirmPassword)
@Html.ValidationMessageFor(model => model.ConfirmPassword)
</div>
希望这有帮助!
答案 1 :(得分:0)
如果您在“RegistrationViewModel”类中添加了属性,则上面的javascript代码是不必要的。
你最好回顾一下原生的MVC样本,这对学习者来说真的是一大财富。