我想在表单中编写一个简单的确认电子邮件验证字段,最好的方法是什么?这是我的代码,直到现在,只是一个基本的形式。对于confirationemail字段,我想有一个像email字段一样的实时验证,而不是像我做的那样只在提交时进行验证:
控制器 public class ContactController : SurfaceController
{
/// <summary>
/// Renders the Contact Form
/// @Html.Action("RenderContactForm","ContactFormSurface");
/// </summary>
/// <returns></returns>
public ActionResult Index()
{
//Return a partial view ContactForm.cshtml in /views/ContactFormSurface/ContactForm.cshtml
//With an empty/new ContactFormViewModel
return PartialView("Contact", new Contact());
}
[HttpPost]
public ActionResult Send(Contact Model)
{
//Check if the dat posted is valid (All required's & email set in email field)
if (!ModelState.IsValid)
{
//Not valid - so lets return the user back to the view with the data they entered still prepopulated
return CurrentUmbracoPage();
}
//Check if the dat posted is valid (All required's & email set in email field)
if (Model.Email != Model.ConfirmEmail)
{
//Not valid - so lets return the user back to the view with the data they entered still prepopulated
return CurrentUmbracoPage();
}
//Update success flag (in a TempData key)
TempData["IsSuccessful"] = true;
TempData["Name"] = Model.Name;
TempData["Email"] = Model.Email;
//All done - lets redirect to the current page & show our thanks/success message
return RedirectToCurrentUmbracoPage();
}
}
模型 namespace CribisWeb.Models
{
public class Contact
{
[Required]
[DisplayName("Nome")]
public string Name { get; set; }
[Required]
[EmailAddress]
[DisplayName("Email")]
public string Email { get; set; }
[Required]
[EmailAddress]
[DisplayName("Conferma Email")]
public string ConfirmEmail { get; set; }
}
}
视图 @model CribisWeb.Models.Contact
@if (Convert.ToBoolean(TempData["IsSuccessful"]))
{
<h1>YAY!</h1>
<p>Thanks for sending your message, we will get back to you shortly.</p>
<p>
@TempData["Name"]
@TempData["Email"]
</p>
}
else
{
using (Html.BeginUmbracoForm<CribisWeb.Controllers.ContactController>("Send"))
{
@Html.ValidationSummary(true)
<div>
<br />
@Html.LabelFor(x => x.Name)
@Html.TextBoxFor(x => x.Name)
@Html.ValidationMessageFor(x => x.Name)
<br />
@Html.LabelFor(x => x.Email)
@Html.TextBoxFor(x => x.Email)
@Html.ValidationMessageFor(x => x.Email)
<br />
@Html.LabelFor(x => x.ConfirmEmail)
@Html.TextBoxFor(x => x.ConfirmEmail)
@Html.ValidationMessageFor(x => x.ConfirmEmail)
<br />
</div>
<input type="submit" value="Submit" class="btn-accept" />
}
}
谢谢
解决了,这真的很容易,在模型:
[Required]
[EmailAddress]
[DisplayName("ConfirmEmail")]
[Compare("Email", ErrorMessage = "The Email and confirmation Email do not match.")]
public string ConfirmEmail { get; set; }