我的表单可以验证有关唯一性的输入电子邮件。
<form id="emailValidationForm">
@Html.ValidationSummary(true, String.Empty, new {@class = "text-danger text-center"})
<div class="form-group text-center">
<div class="input-group margin-bottom-5 margin-top-10">
<span class="input-group-addon"><i class="fa fa-user"></i></span>
@Html.TextBoxFor(m => m.Email, new {@class="form-control", @placeholder="Enter your Email",@data_toggle="tooltip"})
@*<input type="text" name="Email" placeholder="Enter your Email" class="form-control" data-toggle="tooltip">*@
</div>
@Html.ValidationMessageFor(m => m.Email, null, new { @class = "text-danger text-center" })
</div>
<div class="text-right">
<button type="submit" class="btn-u btn-u-wide btn-u-orange" title="Validate email">Join</button>
</div>
</form>
电子邮件是下一个模型的一部分:
public class RegisterViewModel
{
[Required]
[EmailAddress]
[Display(Name = "Email")]
public string Email { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}
所以,当我在文本框中输入任何内容时,我会收到错误。当我输入已经注册的电子邮件时,我也会从检查唯一性的函数中得到错误。
[AllowAnonymous]
public JsonResult EmailValidation(string email)
{
if (ModelState.IsValid)
{
var user = _service.FindByEmail(email);
if (user == null)
{
return Json(new {result = true, message = "Email is validated"}, JsonRequestBehavior.AllowGet);
}
ModelState.AddModelError(string.Empty, "Email already exists");
return Json(new
{
result = false,
message =
RenderRazorViewToString("~/Views/Account/_RegisterPartialView.cshtml",
new RegisterViewModel {Email = email})
}, JsonRequestBehavior.AllowGet);
}
return Json(new {result = false, message = "Input Email"}, JsonRequestBehavior.AllowGet);
}
但是后来客户端验证不起作用,我可以在电子邮件文本框中输入任何内容,它将会继续。
我该如何解决?
我使用jquery 1.10.2和jquery.validate进行验证。研究MVC5。使用Bootstrap3进行样式设计。
我也设置了自定义默认值:
$.validator.setDefaults({
highlight: function (element) {
$(element).closest(".input-group").addClass("has-error");
},
unhighlight: function (element) {
$(element).closest(".input-group").removeClass("has-error");
}
});
该脚本在partialView中(我尝试在partialView上使用的js-module中替换它,但是这不起作用。所以我在partialView中将脚本保留了下来)
答案 0 :(得分:0)
您需要将远程注释添加到电子邮件字段:
[Remote("EmailValidation","<ControllerName>", ErrorMessage="{0} already has an account, please enter a different email address.")]
public string Email { get; set; }
在我看来,你似乎在这里混合了两个概念。验证检查应该是一个简单的JSON结果,如下所示:
public JsonResult EmailValidation(string email)
{
var user = _service.FindByEmail(email);
return user == null
? Json(true, JsonRequestBehavior.AllowGet)
: Json(false, JsonRequestBehavior.AllowGet);
}