我想在表单中编写一个简单的确认电子邮件验证字段,最好的方法是什么?这是我到目前为止的代码,只是一个基本形式。对于确认电子邮件字段,我希望像电子邮件字段一样进行实时验证,而不仅仅是像我一样提交:
控制器
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" />
}
}
谢谢