如何远程验证电子邮件或检查电子邮件是否存在

时间:2013-01-17 03:16:54

标签: c# asp.net-mvc-4 email-validation asp.net-4.5 remote-validation

我正在尝试检查注册时是否存在电子邮件,以便数据库中没有重复的电子邮件。我使用MVC4默认Internet应用程序执行此操作,但我已向RegisterviewModel添加了电子邮件字段。我也注意到,使用UserName字段做得很好,但我不知道他们是如何做到的。我尝试按照下面的博客但没有运气,因为当我点击创建时没有回应。 Tug Berk。当我使用firebug时,我Status: 302 Found

时会收到Json action excutes

这就是我所拥有的:

用户配置

[Table("UserProfile")]
public class UserProfile
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int UserId { get; set; }
    public string UserName { get; set; }
    public string Email { get; set; }
}

RegisterViewModel

public class RegisterModel
{
    [Required]
    [Display(Name = "User name")]
    public string UserName { get; set; }

    [Required]
    [DataType(DataType.EmailAddress)]
    [Display(Name = "Email")]
    [Remote("DoesUserEmailExist", "Account", HttpMethod = "POST", ErrorMessage = "Email address already exists. Please enter a different Email address.")]
    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")]
    [System.ComponentModel.DataAnnotations.Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
    public string ConfirmPassword { get; set; }
}

注册操作

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public ActionResult Register(RegisterModel model)
    {
        if (ModelState.IsValid)
        {
            try //CreateUserAndAccount
            {
                WebSecurity.CreateUserAndAccount(model.UserName, model.Password, new { model.Email });
                WebSecurity.Login(model.UserName, model.Password);
                return RedirectToAction("Index", "Home");

            }
            catch (MembershipCreateUserException e)
            {
                ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
            }
        }

        // If we got this far, something failed, redisplay form
        return View(model);
    }

Json行动

[HttpPost]
    public JsonResult DoesUserEmailExist(string email)
    {

        var user = Membership.GetUserNameByEmail(email);

        return Json(user == null);
    }

编辑:添加了注册视图

     @model Soccer.Models.RegisterModel

     @{
     ViewBag.Title = "Register";
     }

     <hgroup class="title">
     <h1>@ViewBag.Title.</h1>
     <h2>Create a new account.</h2>
     </hgroup>

 @using (Html.BeginForm()) {
 @Html.AntiForgeryToken()
 @Html.ValidationSummary()

 <fieldset>
    <legend>Registration Form</legend>
    <ol>
        <li>
            @Html.LabelFor(m => m.UserName)
            @Html.TextBoxFor(m => m.UserName)
        </li>
        <li>
            @Html.LabelFor(m => m.Email)
            @Html.TextBoxFor(m => m.Email)
        </li>
        <li>
            @Html.LabelFor(m => m.Password)
            @Html.PasswordFor(m => m.Password)
        </li>
        <li>
            @Html.LabelFor(m => m.ConfirmPassword)
            @Html.PasswordFor(m => m.ConfirmPassword)
        </li>
    </ol>
    <input type="submit" value="Register" />
</fieldset>
 }

 @section Scripts {
 @Scripts.Render("~/bundles/jqueryval")
 }

有什么我不该做的事情,还是我可以选择其他更简单的选择?

2 个答案:

答案 0 :(得分:6)

对于首发,我想感谢JOBG通过此与我进行交互。如果您使用Database First因为它要求您在数据库中设置电子邮件列UNIQUE,那么我在上述问题中显示的内容仍然有用,但要使其与EF Code First一起工作我必须这样做以下注册操作,请注意,使用此解决方案,您不需要Remote Annotation in the model

注册操作

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public ActionResult Register(RegisterModel model)
    {
        if (ModelState.IsValid)
        {
            // Insert a new user into the database
            using (UsersContext db = new UsersContext())
            {
                UserProfile email = db.UserProfiles.FirstOrDefault(u => u.Email.ToLower() == model.Email.ToLower());
                try
                {
                    // Check if email already exists
                    if (email == null)
                    {
                        WebSecurity.CreateUserAndAccount(model.UserName, model.Password, new { Email = model.Email });
                        WebSecurity.Login(model.UserName, model.Password);
                        return RedirectToAction("Index", "Home");
                    }
                    else
                    {
                        ModelState.AddModelError("Email", "Email address already exists. Please enter a different email address.");
                    }
                }
                catch (MembershipCreateUserException e)
                {

                    ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
                }
            }
        }

        // If we got this far, something failed, redisplay form
        return View(model);
    }

注意:请注意,此操作会在UserName之前验证电子邮件,并且要求您在创建对象之前至少访问一次数据库。

答案 1 :(得分:2)

很难说没有View代码,但我的第一个嫌疑人是js,请确保你设置了jQuery验证插件,它应该用.blur()事件触发验证,用firebug检查页面(或类似的)并寻找一个ajax POST,当该字段失去焦点时命中DoesUserEmailExist,如果没有发生这种情况,那么客户端缺少某些属性Remote属性和服务DoesUserEmailExist看起来好。

旁注 :确保您在电子邮件字段的数据库中有UNIQUE约束,这是确保您拥有的唯一真正方法由于并发性,即使使用DoesUserEmailExist验证,也没有重复的电子邮件。